2 回答
TA贡献1864条经验 获得超6个赞
虽然您可以通过在 中包含其他属性来修复它setFormState,例如:
setFormState({
name: e.target.value
age,
});
函数组件不是类组件 - 如果它们不相关,请随意将值分离到单独的变量中。这将使语法变得更容易:
const Form = () => {
const [name, setName] = React.useState('John');
const [age, setAge] = React.useState(25);
const handleNameChange = (e) => {
setName(e.target.value);
};
const handleAgeChange = (e) => {
setAge(e.target.value);
};
return (
<form onSubmit={(e) => e.preventDefault()}>
<label htmlFor='name'>Name: </label>
<input type='text' id='name' name='name' placeholder={name} onChange={handleNameChange} />
<p>The person's name is {name}.</p>
<br />
<label htmlFor='age'>Age: </label>
<input type='text' id='age' name='age' placeholder={age} onChange={handleAgeChange} />
<p>His/her age is {age}.</p>
</form>
)
}
ReactDOM.render(<Form />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>
TA贡献1863条经验 获得超2个赞
在useState钩子中,属性不会像以前在setState类组件的函数中那样合并。您必须包含缺失的字段,以将它们保留在对象中。
setFormState({
name: e.target.value,
age,
});
添加回答
举报