react中获取表单输入值
A common scenario involves having a form, and you want to get the value of one of the form fields, for example when the user clicks a button.
常见的情况涉及拥有一个表单,并且您想要获取表单字段之一的值,例如,当用户单击按钮时。
How can you do so?
你该怎么做?
Using hooks, you can create a variable for each input field, and listening on the onChange
event you call the “set” function for that variable.
使用挂钩,您可以为每个输入字段创建一个变量,并在onChange
事件上侦听该变量的“设置”函数。
Here’s an example:
这是一个例子:
const [title, setTitle] = useState('')
And on the input field in JSX:
在JSX的输入字段上:
<input onChange={event => setTitle(event.target.value)} />
In this way, when you are in the event handler for the submit event of the form, or anywhere you want, you can get the value of the field from the title
value.
这样,当您在表单的Submit事件的事件处理程序中或所需的任何位置时,都可以从title
值中获取字段的值。
react中获取表单输入值