我正在使用react-select Latest创建一个异步选择组件。一旦选择一些值,我将尝试更改选择的背景色和边框色。我浏览了文档,并尝试使用 state.isSelected 有条件地更改背景颜色。但是没有帮助。
按如下所示选择值时,我想更改背景颜色以及边框颜色。但是似乎什么也没发生。帮助将不胜感激
答案 0 :(得分:2)
参考文档:反应选择customize styles
您可以覆盖不同域中提供的默认样式。
在这种情况下,基本的控件就足够了。
const customStyles = stateValue => ({
control: (provided, state) => ({
...provided,
backgroundColor: stateValue ? "gray" : "white"
})
});
import React, { useState } from "react";
import Select from "react-select";
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
const customStyles = value => ({
control: (provided, state) => ({
...provided,
alignItems: "baseline",
backgroundColor: value ? "gray" : "white"
})
});
const App = () => {
const [selected, setSelected] = useState("");
const onChange = e => {
setSelected(e.value);
};
const onClickButton = () => {
setSelected("");
};
const displayItem = selected => {
const item = options.find(x => x.value === selected);
return item ? item : { value: "", label: "" };
};
return (
<>
<Select
options={options}
styles={customStyles(selected)}
onChange={onChange}
value={displayItem(selected)}
/>
<button onClick={onClickButton}> Clear Selection </button>
</>
);
};
export default App;