材质ui总是返回0 onchange

时间:2020-08-25 10:32:34

标签: reactjs material-ui

当我尝试更改material-ui的自动完成功能中的值时,我总是得到其值0,在这里,我已经上传了完整的代码,有人可以检查我的代码并帮助我解决此问题吗? 任何帮助将不胜感激。

export default function CreatePIC() {
  const classes = useStyles();
  const Department_list = [
    { label: 'Department1', id: 1 },
    { label: 'Department2', id: 2 },
    { label: 'Department3', id: 3 },
    { label: 'Department4', id: 4},
    { label: 'Department5', id: 5 }
  ]

  const [department, setDepartment] = React.useState('');
  
  const handleChangeDepartment = (event) => {
    console.log(event.target.value);
    setDepartment(event.target.value);
  };

return (
<Autocomplete
                          id="Department"
                          value={department}
                          helperText={error.department}
                          options={Department_list}
                          getOptionLabel={option => typeof option === 'string' ? option : option.label}
                          onChange = {handleChangeDepartment}
                          renderInput={(params) => <TextField {...params} label="Search Department" variant="outlined" placeholder="Add Department"  />}
                        />
)
}

2 个答案:

答案 0 :(得分:0)

Ciao,在Autocomplete组件event.target.value中将始终为0。如果要获取所选部门,可以在value中使用handleChangeDepartment。这样您的代码将变为:

const handleChangeDepartment = (event, values) => {
    console.log(event.target.value);  // print always 0
    console.log(values);              // print values selected like { label: 'Department1', id: 1 } 
    setDepartment(values.label);      // set department with values.label
  };

Here一个代码框示例。

答案 1 :(得分:0)

而不是使用:

event.target.value

尝试使用:

event.target.innerText

或者,要找到选项索引,请使用:

event.target.dataset.optionIndex