如果没有剩余的选项,我需要在过滤时创建带有标签“ Ostatni”的新选项。我尝试通过自定义 MenuList 和 NoOptionsMessage 来做到这一点,但是没有任何效果。有什么办法吗?
NoOptionsMessage = props => (
<components.NoOptionsMessage
{...props}
children={<components.Option {...components.Option.defaultProps} data={{ value: 37, label: 'Ostatni' }} />}
/>
)
答案 0 :(得分:0)
您可以使用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
,以便在存在时始终显示。
答案 1 :(得分:0)
现在似乎可以通过内置组件来实现。
https://react-select.com/creatable
import React, { Component } from 'react';
import CreatableSelect from 'react-select/creatable';
import { colourOptions } from '../data';
export default class CreatableSingle extends Component<*, State> {
handleChange = (newValue: any, actionMeta: any) => {
console.group('Value Changed');
console.log(newValue);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
};
handleInputChange = (inputValue: any, actionMeta: any) => {
console.group('Input Changed');
console.log(inputValue);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
};
render() {
return (
<CreatableSelect
isClearable
onChange={this.handleChange}
onInputChange={this.handleInputChange}
options={colourOptions}
/>
);
}
}