【问题标题】:How to set different values for different material select using states in functional component of react如何使用反应功能组件中的状态为不同的材料选择设置不同的值
【发布时间】:2020-06-18 21:07:11
【问题描述】:

我是新来的反应和使用材料设计选择框, https://material-ui.com/components/selects/

在简单的选择框中有多个可用的选择框,但是当我选择一个选择框选项时,所有剩余的框都设置为相同的选定值。 下面是例子 https://codesandbox.io/s/yk15u

我想在单击它时设置选择框选项值。 提供合适的解决方案

【问题讨论】:

    标签: reactjs select material-ui react-functional-component


    【解决方案1】:

    您必须单独存储该值,在示例中提供的所有Select 都提供了道具value={age}。所以所有字段都指向相同的值状态。

    1. 将年龄状态设为对象而不是字符串
    const initialState = {
     select1: '',
     select2: '',
     ...
    };
    const [age, setAge] = React.useState(initialState); 
    
    1. 在 select 中将 id 传递给 handleChange,并从 ages 属性中设置相应的 value
    <Select
     labelId="demo-simple-select-label"
     id="demo-simple-select"
     value={ages.select1}
     onChange={(e) => handleChange(e, 'select1')}
    >
    ....
    </Select>
    
    1. 触发handleChangeselect 的设置状态
    const handleChange = (event, name) => {
      const newAge = {...age, [name]: event.tatget.value};
      setAge(newAge);
    };
    

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 2022-07-01
      • 2019-02-10
      • 2016-02-13
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多