【问题标题】:Cancel MUI Autocomplete onChange when reason is "create-option"当原因是“create-option”时取消 MUI Autocomplete onChange
【发布时间】:2020-10-26 15:57:06
【问题描述】:

如果该值存在错误,我希望能够不允许用户将输入值添加到自动完成的值数组,但我也想保留当前正在输入的输入值。有没有办法取消活动?

<Autocomplete
    multiple
    options={[]}
    freeSolo
    onChange={(event, value, reason) => {
        if (reason === 'create-option' && error) {
        // prevent this event from going through
        }
    }}
    ...
/>

感谢您的帮助!

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    这本身并不是对上述问题的解决方案,而是解决了我的问题。

    const [inputValue, setInputValue] = useState('');
    
      return (
        <Autocomplete
          multiple
          options={[]}
          freeSolo
          renderTags={(values: string[], getTagProps) => {
            return values.map((option: string, index: number) => {
              if (!option) return;
              return (
                <Chip
                  variant="outlined"
                  label={option}
                  {...getTagProps({ index })}
                />
              );
            });
          }}
          inputValue={inputValue}
          onChange={(event: any, values: any, reason: string) => {
            if (reason === 'create-option' && form.getState().errors.verses) {
              setInputValue(values[values.length - 1]);
              values[values.length - 1] = null;
            } else {
              setInputValue('');
            }
          }}
    />
    

    如果您将 inputValue 设置为自动完成,然后将持久值设置为 null,您可以保留输入值而不保存不需要的值,这样用户就不必重新开始输入。如果值有效,则将输入值设置为空字符串。

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      相关资源
      最近更新 更多