您可以使用filterOption 函数实现您的目标,如下代码:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
hasExtraValue: false,
options: [
{ label: "Label 1", value: 1 },
{ label: "Label 2", value: 2 },
{ label: "Label 3", value: 3 },
{ label: "Label 4", value: 4 },
{ label: "Label 5", value: 5 },
{ label: "Label 6", value: 6 },
{ label: "Label 7", value: 7 },
{ label: "Label 8", value: 8 },
{label: 'Ostatni', value: 'other'}
]
};
}
filterOption = (option, inputValue) => {
// tweak the filterOption to render Ostatni only if there's no other option matching + set hasExtraValue to true in case you want to display an message
if (option.label === "Ostatni"){
const {options} = this.state
const result = options.filter(opt => opt.label.includes(inputValue))
this.setState({ hasExtraValue: !result.length})
return !result.length
};
return option.label.includes(inputValue);
};
render() {
return (
<div>
<Select
isMulti
filterOption={this.filterOption}
noOptionsMessage={() => "No more options"}
options={this.state.options}
/>
// Displays a user friendly message to explain the situation
{this.state.hasExtraValue && <p>Please select 'Ostatni' option if you don't find your option !</p>}
</div>
);
}
}
这个想法是在用户输入内容时触发。如果没有可用的选项,您可以添加一个新的所需标签以向用户提供新选项。
在filterOption 中,您将此特殊选项设置为始终为true,因此如果存在,它将始终显示。
Here a live example.