我使用的是react-select v2 (2.41)。我有3个选项设置,我想设置每个选项的背景颜色为不同的颜色。这是可能的吗?如何实现?
我尝试过这样的风格:
const customStyle = {
option: (base, state) => ({
...base,
backgroundColor: "red",
})
};
<Select
...
options={options}
styles={customStyle}
/>但这会将所有选项的颜色更改为相同的颜色。我想要的是每个选项都有不同的背景颜色。如下所示:

发布于 2019-03-08 04:10:36
您可以使用component道具在options props上设置背景色,如下所示:
const Option = props => {
return (
<div style={{ backgroundColor: props.data.color }}>
<components.Option {...props} />
</div>
);
};
const options = [
{ label: "Option 1", value: 1, color: "red" },
{ label: "Option 2", value: 2, color: "orange" },
{ label: "Option 3", value: 3, color: "green" }
];
function App() {
return (
<div className="App">
<Select options={options} components={{ Option }} />
</div>
);
}就像在这个live example中。
发布于 2019-03-08 03:02:27
使用:nth-child() CSS选择器怎么样?
<Select
...
className="myclass"
classNamePrefix="myclass"
options={options}
styles={customStyle}
/>
// CSS
.myclass__value-container:nth-child(1) {
// rules
}
.myclass__value-container:nth-child(2) {
// rules
}
.myclass__value-container:nth-child(3) {
// rules
}发布于 2019-08-21 20:47:20
另一种实现您想要做的事情的方法是使用react选择样式
文档:https://react-select.com/styles
示例:
const colorsArray = [
{ label: "Option 1", value: 1, color: '#FF8B8B' },
{ label: "Option 1", value: 2, color: '#ABFF8B' },
{ label: "Option 1", value: 3, color: '#80CEAC' },
];
const colorStyles = {
option: (styles, { data }) => {
return {
...styles,
backgroundColor: data.color,
};
},
};
<Select
value={colorsArray[0]}
options={colorsArray}
styles={colorStyles}
/>https://stackoverflow.com/questions/55050905
复制相似问题