头图

Original link: https://bobbyhadz.com/blog/react-get-form-input-value-on-submit

Author: Borislav Hadzhiev

The text starts here~

Overview

In React, the value of input is obtained through form submission:

  1. Store the value of the input control in the state variable.
  2. Set the onSubmit attribute on the form form.
  3. Access the value of the input control in the handleSubmit function.
 import {useState} from 'react';

const App = () => {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');

  const handleSubmit = event => {
    console.log('handleSubmit ran');
    event.preventDefault(); // 👈️ prevent page refresh

    // 👇️ access input values here
    console.log('firstName 👉️', firstName);
    console.log('lastName 👉️', lastName);

    // 👇️ clear all input values in the form
    setFirstName('');
    setLastName('');
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          id="first_name"
          name="first_name"
          type="text"
          onChange={event => setFirstName(event.target.value)}
          value={firstName}
        />
        <input
          id="last_name"
          name="last_name"
          type="text"
          value={lastName}
          onChange={event => setLastName(event.target.value)}
        />

        <button type="submit">Submit form</button>
      </form>
    </div>
  );
};

export default App;

get-form-input-value-on-submit.gif

controlled controls

We use the useState hook to track the value of the input control. We set the onChange property on the control, so when the value on the control is updated, we update the corresponding state variable.

form表单上的button元素具有submit类型,所以每当按钮被点击时, form表单上的submit The event will be triggered.

When the form form is submitted, we use event.preventDefault() in the handleSubmit function to prevent the form form from refreshing the page ---a4322dab68078f2

To get the input value when the form is submitted, we just need to access the state variable. If you want to clear the control value after the form is submitted, you can set the state variable to an empty string.

uncontrolled controls

Similarly, uncontrolled input controls can be used.

  1. Set the ref property on each input control.
  2. Set the onSubmit attribute on the form element.
  3. Access the value of input --- on the ref object, for example, ref.current.value .
 import {useRef} from 'react';

const App = () => {
  const firstRef = useRef(null);
  const lastRef = useRef(null);

  const handleSubmit = event => {
    console.log('handleSubmit ran');
    event.preventDefault(); // 👈️ prevent page refresh

    // 👇️ access input values here
    console.log('first 👉️', firstRef.current.value);
    console.log('last 👉️', lastRef.current.value);

    // 👇️ clear all input values in the form
    event.target.reset();
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          ref={firstRef}
          id="first_name"
          name="first_name"
          type="text"
        />
        <input
          ref={lastRef}
          id="last_name"
          name="last_name"
          type="text"
        />

        <button type="submit">Submit form</button>
      </form>
    </div>
  );
};

export default App;

The above example uses an uncontrolled input control. It should be noted that the input control has no onChange attribute or value setting.

You can use the defaultValue attribute to pass an initial value to an uncontrolled input . However, this is not required, you can omit this property if you don't want to set the initial value.

When using an uncontrolled input control, we use ref to access input element. useRef() hook can be passed an initial value as a parameter. The hook returns a mutable ref object whose .current property is initialized to the passed parameter.

ref ,我们必须访问current ,以ref input .

当我们为元素传递ref属性时,比如说, <input ref={myRef} /> ,React ref .current的DOM node.

useRef The hook creates a normal JavaScript object, but gives you the same ref object on every render. In other words, it's pretty much a memoized object value with the .current attribute.

It should be noted that when you change the value of the ref current property of ---8543b671ceab8b5fe70ab57642f16320---, it will not cause a re-render. Whenever the user submits the form, the value of uncontrolled input is printed.

You should not set the value property on an uncontrolled input (an input control without a onChange handler), as this will make the input control unusable change, you won't be able to type in it.

reset

If you want to clear the uncontrolled input value after the form is submitted, you can use the reset() method.

reset() method restores the default value of the form element. No matter how many uncontrolled input controls your form has, just call the reset() method to clear all fields.

Another way to get the value of an input control when the form is submitted is to access the form element using the name attribute.

 const App = () => {
  const handleSubmit = event => {
    console.log('handleSubmit ran');
    event.preventDefault();

    // 👇️ access input values using name prop
    console.log('first 👉️', event.target.first_name.value);
    console.log('second 👉️', event.target.last_name.value);

    // 👇️ clear all input values in the form
    event.target.reset();
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          id="first_name"
          name="first_name"
          type="text"
        />
        <input
          id="last_name"
          name="last_name"
          type="text"
        />

        <button type="submit">Submit form</button>
      </form>
    </div>
  );
};

export default App;

event target Attribute reference on the form element on the object.

You won't see this method very often, it can be used if you don't want to store the value of the input control in state or use the ref object. This is mostly a quick and untidy solution.

The most common way is to store the input value in the state variable. The ability to access state variables from anywhere allows for highly customizable forms.


chuck
300 声望41 粉丝