React-select creatable - 只允许创建一个选项
React-select creatable - only allow one created option
我正在使用 react-select and the creatable function that allows you to create a new select option - just type in the select/input field on 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);
};
你可以做的是存储新选项的索引,检查是否存储了索引,如果有,用新的索引替换这个值,就像下面的代码:
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);
};
我正在使用 react-select and the creatable function that allows you to create a new select option - just type in the select/input field on 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);
};
你可以做的是存储新选项的索引,检查是否存储了索引,如果有,用新的索引替换这个值,就像下面的代码:
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);
};