2 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
雖然您可以通過在 中包含其他屬性來(lái)修復(fù)它setFormState,例如:
setFormState({
name: e.target.value
age,
});
函數(shù)組件不是類組件 - 如果它們不相關(guān),請(qǐng)隨意將值分離到單獨(dú)的變量中。這將使語(yǔ)法變得更容易:
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貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
在useState鉤子中,屬性不會(huì)像以前在setState類組件的函數(shù)中那樣合并。您必須包含缺失的字段,以將它們保留在對(duì)象中。
setFormState({
name: e.target.value,
age,
});
添加回答
舉報(bào)