选择时如何更改react选择选项样式
IT技术
javascript
html
css
reactjs
react-select
2021-05-20 02:46:39
1个回答
方法
参考文档:react-select自定义样式
您可以覆盖不同域中默认提供的样式。
在这种情况下,基本控制就足够了。
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;