1. 使用 state 实现双向绑定
对于双向绑定,需要同时处理表单元素的`value`属性(通过`state`来设置)和`onChange`事件(用于更新`state`)。
javascript
import { useState } from "react";
const MyComponent = () => {
const [inputValue, setInputValue] = useState("");
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<div>
<input type="text" value={inputValue} onChange={handleChange} />
<p>You entered: {inputValue}</p>
</div>
);
};
2. 多个表单元素的双向绑定
例如表单中有多个输入框,可以为每个表单元素创建一个独立的状态变量,或者使用一个对象来存储所有表单元素的值。
javascript
import { useState } from "react";
const MyFormComponent = () => {
const [formData, setFormData] = useState({
name: "",
email: "",
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("Form submitted:", formData);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
};