如果该值不在数据源中,如何重置 antd 自动完成的值
How to reset the value of antd autocomplete, if the value is not in the data source
我正在使用 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()
但没有成功。谁能帮我解决这个问题?
提前致谢
在 AutoComplete 标签中设置值属性,并为其设置状态,检查是否找不到搜索值将状态更改为初始状态。
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}
/>
这对我有用。
我正在使用 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()
但没有成功。谁能帮我解决这个问题?
提前致谢
在 AutoComplete 标签中设置值属性,并为其设置状态,检查是否找不到搜索值将状态更改为初始状态。
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}
/>
这对我有用。