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:
- Store the value of the input control in the
state
variable. - Set the
onSubmit
attribute on theform
form. - 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;
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 theform
form is submitted, we useevent.preventDefault()
in thehandleSubmit
function to prevent theform
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.
- Set the
ref
property on each input control. - Set the
onSubmit
attribute on theform
element. - Access the value of
input
--- on theref
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 thedefaultValue
attribute to pass an initial value to an uncontrolledinput
. 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 sameref
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 uncontrolledinput
value after the form is submitted, you can use thereset()
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 instate
or use theref
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.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。