gpt4 book ai didi

reactjs - 如何更改 react-select 所选选项的样式?

转载 作者:行者123 更新时间:2023-12-05 04:34:58 25 4
gpt4 key购买 nike

现在 react-select 会像这样显示选定的选项 enter image description here

但是如果我们从 20 个选项中选择 10 个,那么这个 block 就会扩展。因此,与其显示每个选择的选项,不如像这样只显示第一个选择的选项+剩余选择的选项数会更好

enter image description here

我如何在 react-select 中实现这一点?

最佳答案

我刚刚编写了这段代码,我认为它可以帮助你。这是实时链接 https://djdz48.csb.app/和下面的片段:

const App = () => {
const maxOptions = 2; // You can change the value

const [values, setValues] = useState([]); // All values (in console)
const [maxValues, setMaxValues] = useState({});
const [isMaxVal, setIsMaxVal] = useState(false);

const [actualOptions, setActualOptions] = useState(options);

const handleChange = (e) => {
let els = [];
e.map((el) => els.push(el));

if (els.length > maxOptions || values.length > maxOptions) {
if (els.length === 0) {
setValues(els);
setIsMaxVal(false);
} else {
setIsMaxVal(true);

const val = {
key: 1,
label: values[0]["label"] + " +" + (values.length + 1).toString()
};

setValues((values) => {
return [...values, els[els.length - 1]];
});

setMaxValues(val);

let opt = [];

options.map((el) => {
if (!values.includes(el) && !els.includes(el)) {
opt.push(el);
}
});

setActualOptions(opt);
}
} else {
setValues(els);
}
};

// values in real time

useEffect(() => {
console.log(values);
}, [values]);

return (
<div className="App">
<Select
options={isMaxVal ? actualOptions : options}
isMulti={true}
onChange={(e) => handleChange(e)}
value={values.length <= maxOptions ? values : maxValues}
/>
</div>
);
};

export default App;

关于reactjs - 如何更改 react-select 所选选项的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71138364/

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