30秒学会 React 片段 · 2023年6月8日

30秒学会 React 片段 – React useForm hook

Creates a stateful value from the fields in a form.

  • Use the useState() hook to create a state variable for the values in the form.
  • Create a function that will be called with an appropriate event by a form field and update the state variable accordingly.

代码实现

const useForm = initialValues => {
  const [values, setValues] = React.useState(initialValues);

  return [
    values,
    e => {
      setValues({
        ...values,
        [e.target.name]: e.target.value
      });
    }
  ];
};

使用样例

const Form = () => {
  const initialState = { email: '', password: '' };
  const [values, setValues] = useForm(initialState);

  const handleSubmit = e => {
    e.preventDefault();
    console.log(values);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" name="email" onChange={setValues} />
      <input type="password" name="password" onChange={setValues} />
      <button type="submit">Submit</button>
    </form>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <Form />
);

翻译自:https://www.30secondsofcode.org/react/s/use-form