gpt4 book ai didi

reactjs - 在 react 选择中排序

转载 作者:行者123 更新时间:2023-12-02 17:01:11 25 4
gpt4 key购买 nike

我想知道是否可以将所有选中的选项都显示在列表的顶部,然后按字母顺序对所有选中的选项进行排序?或者至少让它们出现在顶部。提前谢谢你。

最佳答案

为了实现您的目标,您可以使用 onChange Prop 来重新排序存储在 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 .

关于reactjs - 在 react 选择中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54113272/

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