0

我想简化表单创建,避免为每个字段编写value={}onChange={}使用自定义钩子。

这是我的代码: https ://codesandbox.io/s/busy-noether-pql8x?file=/src/App.js

问题是,每次我按下按钮时,除了我当前编辑的字段外,状态都会被清除

4

1 回答 1

0
import React, { useState } from "react";
import "./styles.css";

const useFormField = (initialValue) => {
  const [values, setValues] = React.useState(initialValue);
  const onChange = React.useCallback((e) => {
    const name = e.target.name;
    const value = e.target.value;
    setValues( (prevValues) =>  ({...prevValues,[name]:value}));
  }, []);
  return { values, onChange };
};

export default function App() {
 

  //hoot to simplify the code,
  const {values,onChange} = useFormField({
    Salary: "",
    Email: ""
  })

  const onCreateUser = () => {
    console.log(values);
  };

  return (
    <div className="App">
      <form>
        <label htmlFor="Email">Email: </label>
        <input name="Email" onChange={onChange}  />
        <label htmlFor="Email">Salary: </label>
        <input name="Salary" onChange={onChange}  />
        <button type="button" onClick={onCreateUser}>
          Send
        </button>
      </form>
    </div>
  );
}
于 2020-12-21T10:42:10.847 回答