通过使用useState钩子来创建一个状态变量,你可以同时获取多个Input框的值。
1获取input框的值:
import React, { useState } from 'react'; function MyComponent() { const [forms, setForms] = useState({ name: '', nation: '', }); const handleInputChange = (e) => { const { name, value } = e.target; setForms((prevForms) => ({ ...prevForms, [name]: value, })); }; const handleSubmit = (e) => { e.preventDefault(); console.log('姓名:', forms.name); console.log('国家:', forms.nation); // 执行其他逻辑 }; return ( <div> <form onSubmit={handleSubmit}> <input type="text" name="name" value={forms.name} onChange={handleInputChange} /> <input type="text" name="nation" value={forms.nation} onChange={handleInputChange} /> {/* 添加其他Input框 */} <button type="submit">提交</button> </form> </div> ); } export default MyComponent;
2获取select框的值
import { useState } from 'react'; import { Select } from 'antd'; const { Option } = Select; const YourComponent = () => { const [forms, setForms] = useState({ name: "", nation: "" }); const handleNameChange = (value) => { setForms(prevState => ({ ...prevState, name: value })); }; const handleNationChange = (value) => { setForms(prevState => ({ ...prevState, nation: value })); }; return ( <> <Select value={forms.name} onChange={handleNameChange}> <Option value="John">John</Option> <Option value="Jane">Jane</Option> <Option value="Bob">Bob</Option> </Select> <Select value={forms.nation} onChange={handleNationChange}> <Option value="USA">USA</Option> <Option value="Canada">Canada</Option> <Option value="UK">UK</Option> </Select> </> ); };