gpt4 book ai didi

javascript - 如果在 React-Select v2 中搜索时没有剩余选项,如何创建新选项?

转载 作者:行者123 更新时间:2023-12-03 00:32:45 25 4
gpt4 key购买 nike

如果没有剩余选项,我需要在过滤时创建带有标签“Ostatni”的新选项。我尝试通过自定义 MenuListNoOptionsMessage 来做到这一点,但没有任何效果。有什么办法吗?

NoOptionsMessage = props => (
<components.NoOptionsMessage
{...props}
children={<components.Option {...components.Option.defaultProps} data={{ value: 37, label: 'Ostatni' }} />}
/>
)

最佳答案

您可以使用 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 .

关于javascript - 如果在 React-Select v2 中搜索时没有剩余选项,如何创建新选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53788057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com