在 react-select 中排序
Sorting in react-select
我想知道是否可以将所有选中的选项都显示在列表的顶部,然后按字母顺序对所有选中的选项进行排序?
或者至少让它们出现在顶部。
提前谢谢你。
为了实现您的目标,您可以使用 onChange
道具来重新排序存储在 state
中的选项,如下所示:
function compare(a, b) {
return a.label > b.label ? 1 : b.label > a.label ? -1 : 0;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
options: options
};
}
onChange = newOptions => {
// take original options and remove selected options
const stateOptions = options.filter(
option => !newOptions.find(op => op === option)
);
// sort the selected options
const orderedNewOptions = newOptions.sort(compare);
this.setState({
// concat the two arrays
options: orderedNewOptions.concat(stateOptions)
});
};
render() {
return (
<Select
isMulti
hideSelectedOptions={false}
options={this.state.options}
onChange={this.onChange}
/>
);
}
}
您需要使用 hideSelectedOptions={false}
来防止隐藏选定的选项。
这里是live example.
我想知道是否可以将所有选中的选项都显示在列表的顶部,然后按字母顺序对所有选中的选项进行排序? 或者至少让它们出现在顶部。 提前谢谢你。
为了实现您的目标,您可以使用 onChange
道具来重新排序存储在 state
中的选项,如下所示:
function compare(a, b) {
return a.label > b.label ? 1 : b.label > a.label ? -1 : 0;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
options: options
};
}
onChange = newOptions => {
// take original options and remove selected options
const stateOptions = options.filter(
option => !newOptions.find(op => op === option)
);
// sort the selected options
const orderedNewOptions = newOptions.sort(compare);
this.setState({
// concat the two arrays
options: orderedNewOptions.concat(stateOptions)
});
};
render() {
return (
<Select
isMulti
hideSelectedOptions={false}
options={this.state.options}
onChange={this.onChange}
/>
);
}
}
您需要使用 hideSelectedOptions={false}
来防止隐藏选定的选项。
这里是live example.