【问题标题】:react- cleaning autocomplete generates an errorreact-cleaning 自动完成会产生错误
【发布时间】:2020-01-09 01:04:05
【问题描述】:

我有一个使用 material-ui 创建的表单,我有一个使用自动完成的文本字段,其中填充了一个 useEffect,负责从 API 中获取数据以加载 AUTOCOMPLETE。

数据未保存。

代码

  const defaultProps={
    options:location.name,
    getOptionLabel: option =>  option.label + "-" + option.phone,
  };


  <Autocomplete
        style={{ width: 300 }}
        {...defaultProps}
        id="city"
        autoComplete                   
        onChange={(event, newVal)=>onChange({target:{name:"name",value: newVal.label }}
          )}
        renderInput={params => (
          <TextField {...params}   label="Country"  margin="normal" variant="outlined" inputProps={{
            ...params.inputProps,
          }}/>
        )}

是什么导致了这种行为?

【问题讨论】:

  • “点击清除”时运行什么代码?

标签: reactjs material-ui react-hooks


【解决方案1】:

您的问题出现在以下行:

onChange={(event, newVal)=&gt;onTagsChange({target:{name:"label",value: newVal.label }}

可能与清除后newValue为null有关。您可以添加保护,例如:

value: newVal || newVal.label

由于我不清楚您如何使用生成的选择,我建议的保护可能不合适。

您可能还想看看他们在文档 (https://material-ui.com/components/autocomplete/#playground) 中使用value 属性来控制AutoComplete 的“受控”示例:

<Autocomplete
 {...defaultProps}
 id="controlled-demo"
 value={value}
 onChange={(event, newValue) => {
  setValue(newValue);
 }}
 renderInput={params => (
  <TextField {...params} label="controlled" margin="normal" fullWidth />
 )}
/>

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2015-10-07
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    相关资源
    最近更新 更多