【问题标题】:How to reset the value of antd autocomplete, if the value is not in the data sourceantd autocomplete的值如何重置,如果值不在数据源中
【发布时间】:2020-07-22 19:25:06
【问题描述】:

我正在使用 ant design AutoComplete 进行位置选择。数据源是一个数组。这是我的代码。

<Form.Item
   label={t("City")}
   name="location"
   rules={[
      {
          required: true,
          message: t("Please enter your city"),
      },
   ]}
   >
       <AutoComplete
          options={this.props.cityList}
          allowClear={true}
          placeholder={t("Enter your city")}
          className="ant-select-custom"
          filterOption={(inputValue, option) =>
             option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
          }
       />
</Form.Item>

问题是,我可以输入任何不在数据源中的内容。我希望它限制它。如果我输入了不在数据源中的内容,则应该删除该值。我试过onBlur()onChange() 但没有运气。谁能帮我解决这个问题?

提前致谢

【问题讨论】:

    标签: reactjs autocomplete antd


    【解决方案1】:

    在 AutoComplete 标签中设置 value props,并为其设置一个 state,检查是否未找到 value on search 将 state 更改为初始状态。

    const [value, setValue] = useState('');
    
    const handleSearch = async val => {
        if (val) {
          const response = await dispatch(yourAction(val));
          if (!response?.length) {
            ...
            setValue(''); // this will clear the input
          } else {
            ...
          }
        } else {
          ...
        }
    };
    
    <AutoComplete
     ...,
     value={value}
    />
    

    这对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 2021-05-11
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多