【问题标题】:How to set different values for different material select using states in functional component of react如何使用反应功能组件中的状态为不同的材料选择设置不同的值
【发布时间】:2020-06-18 21:07:11
【问题描述】:
【问题讨论】:
标签:
reactjs
select
material-ui
react-functional-component
【解决方案1】:
您必须单独存储该值,在示例中提供的所有Select 都提供了道具value={age}。所以所有字段都指向相同的值状态。
- 将年龄状态设为对象而不是字符串
const initialState = {
select1: '',
select2: '',
...
};
const [age, setAge] = React.useState(initialState);
- 在 select 中将 id 传递给 handleChange,并从
ages 属性中设置相应的 value。
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={ages.select1}
onChange={(e) => handleChange(e, 'select1')}
>
....
</Select>
- 触发
handleChange 的select 的设置状态
const handleChange = (event, name) => {
const newAge = {...age, [name]: event.tatget.value};
setAge(newAge);
};