我有以下代码,只是想更新输入字段更改时的文本值。
import React, { useState } from 'react';
const Form = () => {
const initialState = {
name: 'John',
age: 25
};
const [{ name, age }, setFormState] = useState(initialState);
const handleNameChange = (e) => {
setFormState({
name: e.target.value
});
};
const handleAgeChange = (e) => {
setFormState({
age: 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>
</>
)
}
export default Form;
这里有一个工作示例:https://codesandbox.io/s/react-playground-forked-tskj9 ?file=/Form.js
问题是,当在姓名字段中输入值时,年龄字段会被清除,反之亦然。我知道这可能是由于initialState
字段更改后不再有效,但是如何保留一个字段中的值<input>
并<p>
在另一个字段中输入值?
慕尼黑的夜晚无繁华
小唯快跑啊
相关分类