如何在react-select的isDisabled为true时修改选择框的背景色
解决方案
你当前仅配置了下拉选项(option)节点的样式,要修改选择框本体的禁用状态背景,需要新增control节点的样式配置:react-select将组件拆分为多个可单独自定义样式的节点,选择框本体对应control节点,isDisabled状态会作为参数传入该节点的样式回调函数中,直接判断状态设置背景色即可。
修改后完整代码如下:
import React from "react"; import Select from "react-select"; const colourOptions = [ { value: "red", label: "Red" }, { value: "green", label: "Green" }, { value: "blue", label: "Blue" } ]; const colourStyles = { // 新增control节点的样式配置,对应选择框本体 control: (styles, { isDisabled }) => { return { ...styles, // 禁用状态下自定义背景色,可替换为你需要的色值 backgroundColor: isDisabled ? "#e9ecef" : "#fff", // 可选:同步修改禁用状态下的边框、鼠标样式 borderColor: isDisabled ? "#dee2e6" : styles.borderColor, cursor: isDisabled ? "not-allowed" : styles.cursor } }, option: (styles, { data, isDisabled, isFocused, isSelected }) => { console.log({ data, isDisabled, isFocused, isSelected }); return { ...styles, backgroundColor: isFocused ? "#999999" : null, color: "#333333" }; } }; export default () => ( <Select defaultValue={colourOptions[1]} label="Single select" options={colourOptions} styles={colourStyles} isDisabled={true} /> );
修改后效果和你预期一致,参考示意图:
内容的提问来源于stack exchange,提问作者Rozani
相关产品推荐
相关产品推荐

