[英]Show the selected option as the first option in the select dropdown?
I am using react-select to show a list of users in a dropdown.我正在使用 react-select 在下拉列表中显示用户列表。 I want it to always show the selected element as the first element in the list.我希望它始终将所选元素显示为列表中的第一个元素。 Is there native support for this?是否有本地支持?
Example:例子:
In the following image, since Green
is selected, I want Green
to appear at the top of the list before Ocean
在下图中,由于选择了Green
,我希望Green
出现在Ocean
之前的列表顶部
You can pass an initialize callback to useState
to sort the options
array for the first time and put the defaultValue
on top:您可以将初始化回调传递给useState
以对options
数组进行第一次排序并将defaultValue
放在顶部:
const defaultValue = initialOptions[5];
const [options] = React.useState(() =>
initialOptions.sort((a, b) => {
if (a === defaultValue) return -1;
if (b === defaultValue) return 1;
return 0;
})
);
return <Select defaultValue={defaultValue} name="colors" options={options} />;
Try this Code :试试这个代码:
const [options, setOptions] = useState([
{ label: "Blue", value: "Blue" },
{ label: "Red", value: "Red" },
{ label: "Yellow", value: "Yellow" },
{ label: "Green", value: "Green" },
{ label: "Pink", value: "Pink" },
{ label: "White", value: "White" },
{ label: "Brown", value: "Brown" }
]);
const [value, setValue] = useState("Select");
function handler(e) {
setValue(e);
let newOptions = [];
newOptions.push({ label: e, value: e });
for (let i in options) {
if (options[i].value !== e) {
newOptions.push(options[i]);
}
}
setOptions(newOptions);
}
return (
<div className="App">
<Select
name="colors"
defaultValue={value}
options={options}
onChange={(e) => handler(e.value)}
/>
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.