我正在使用react-select和可创建函数,该函数可让您创建新的选择选项-只需在example上的选择/输入字段中输入即可。
我想进行一次检查,一次只允许创建一个可创建的选项,下一个创建的选项将删除并取代前一个。目前,您可以创造无限量。
这是处理创建的选项的部分,所以我想我需要添加某种规则以仅在此处允许一个选项。
任何帮助表示赞赏。
handleCreate = input => (inputValue: any) => {
this.setState({ isLoading: true });
setTimeout(() => {
const { options } = this.state;
const newOption = createOption(inputValue);
this.setState({
isLoading: false,
options: [...options, newOption],
value: newOption
});
input.onChange(newOption);
}, 1000);
};
答案 0 :(得分:1)
您可以做的是存储新选项的索引,检查是否存储了索引,如果是,则用新的替换此值,如以下代码:
state = {
value: this.props.options[0],
options: this.props.options,
hasCreatedOption: false
};
handleCreate = input => (inputValue: any) => {
this.setState({ isLoading: true });
setTimeout(() => {
const { options } = this.state;
const newOption = createOption(inputValue);
let hasCreatedOption = false;
if (this.state.hasCreatedOption) {
options[this.state.hasCreatedOption] = newOption;
} else {
options.push(newOption);
}
hasCreatedOption = options.length - 1;
this.setState({
hasCreatedOption,
isLoading: false,
options: [...options],
value: newOption
});
input.onChange(newOption);
}, 1000);
};