【问题标题】:React material-ui multiple checkboxes and onChange not working反应材料-ui多个复选框和onChange不起作用
【发布时间】:2022-01-04 07:30:06
【问题描述】:

我在一个编辑模式表单中有多个复选框,它有一个用于更新的记录结构,包含输入,包括状态中的复选框。 输入有一个 onChange 事件。

当我点击一个复选框时,onChnage 'handleInputChanges' 会执行。 evt.target.checked 是真还是假。 evt.target.name 是正确的,并且与 updateRecordStructure 中的名称匹配。

但复选框不会显示选中或未选中状态。

标记:

<Grid item xs={5}>
    <FormControlLabel variant="outlined" size="small"
         control={<Checkbox
         checked={defaultChecked}
         color="primary"
         name={name}
         onChange={handleInputChanges}/>
        }
        label={label}
        id={id}
    />
</Grid>

    const updateRecordStructure ={
            id: 0,
            name: '',
            canDo1b: false,
            canDo1a: false,
            canDo2b: false,
            canDo2a: false
 };
     
 const [editRecordState, setEditRecordState] = React.useState(
    updateRecordStructure
);

   const handleInputChanges = (evt) => {
    //  Distinguish which input the change is coming from using the target.name.
    //  The square brackets around target.name, creates a dynamic key of that targets name in the object.
      
    if (evt.target.name !== '') {
        const value = evt.target.value;

         if (evt.target.checked) {
            setEditRecordState({
                ...editRecordState,
                [evt.target.name]: evt.target.checked
            });
        } else {
            setEditRecordState({
                ...editRecordState,
                [evt.target.name]: value
            });
        }
    }
};

【问题讨论】:

    标签: reactjs checkbox material-ui react-state


    【解决方案1】:

    您的状态甚至没有连接到复选框。

    您的代码:

    <Grid item xs={5}>
      <FormControlLabel variant="outlined" size="small"
        control={
          <Checkbox
            checked={defaultChecked} // You are supposed to specify your state here
            color="primary"
            name={name}
            onChange={handleInputChanges}
          />
        }
        label={label}
        id={id}
      />
    </Grid>
    

    <Grid item xs={5}>
      <FormControlLabel variant="outlined" size="small"
        control={
          <Checkbox
            checked={editRecordState[name]}
            color="primary"
            name={name}
            onChange={handleInputChanges}
          />
        }
        label={label}
        id={id}
      />
    </Grid>
    

    如果您希望默认选中某些复选框,请改为更新 updateRecordStructure

    【讨论】:

      猜你喜欢
      • 2020-10-29
      • 2018-11-08
      • 2021-05-29
      • 2017-09-02
      • 1970-01-01
      • 2021-05-20
      • 2021-10-06
      • 2017-02-01
      • 2020-11-29
      相关资源
      最近更新 更多