[英]Unable to change selected option background color | React Select
我正在為我的下拉選擇使用 React select 組件。 所有功能都工作正常,但是當從下拉列表中選擇選項時,我無法設置所選選項背景顏色的樣式。 嘗試了幾個選項,但這也不起作用。
以下是相同的代碼:-
import React, { useContext, useState } from "react";
import moment from "moment";
import Select from "react-select";
import DataProvider from "context/DataContext";
export default function Compare() {
const [selectedValue, setSelectedValue] = useState([]);
const {
fromDate,
toDate,
} = useContext(DataProvider);
const customStyles = {
option: (base, state) => ({
...base,
color: "#1e2022",
backgroundColor: state.isSelected ? "rgba(189,197,209,.3)" : "white",
padding: ".5rem 3rem .5rem .5rem",
cursor: "pointer",
}),
singleValue: (provided, state) => {
const opacity = state.isDisabled ? 0.5 : 1;
const transition = "opacity 300ms";
return { ...provided, opacity, transition };
},
};
const options = [
{
value: [
moment(fromDate).subtract(1, "days"),
moment(toDate).subtract(1, "days"),
],
label: "Previous Day",
},
{
value: [
moment(fromDate).subtract(7, "days"),
moment(toDate).subtract(7, "days"),
],
label: "Previous Week",
},
];
const handleApply = (event) => {
setSelectedValue(event);
};
return (
<Select
onChange={handleApply}
options={options}
styles={customStyles}
placeholder="Compare to Past"
/>
);
}
有一個關於此的問題。 顯然 isSelected 僅用於多選。 對於單選,您可以檢查:
state.data === state.selectProps.value
https://github.com/JedWatson/react-select/issues/3817
[編輯]這看起來真的很奇怪,但看起來如果你在組件之外聲明選項它就可以工作。 檢查這里。 如果您復制了渲染函數中的選項,則樣式將不起作用。 當我嘗試將值設置為“1”和“2”時,值是日期或時刻對象或其他東西不是問題。
[Edit 2] Ok emm .. 我將它重構為一個功能組件,它可以與組件內部的選項一起使用。 我猜這可能是使用鈎子的問題。 要查看的沙箱相同。
你可以利用 hasValue 道具代替
https://github.com/JedWatson/react-select/issues/3817#issuecomment-547487812
backgroundColor: state.hasValue ? "rgba(189,197,209,.3)" : "white",
為了僅更改所選選項的背景顏色,請嘗試以下操作:
option: (provided, state) => ({
...provided,
backgroundColor: state.isSelected ? "rgba(189,197,209,.3)" : "white",
}),
附加到上面@Nathan的答案,如果您不希望在 hover 上更改背景顏色,請包含 &hover
option: (provided, state) => ({
...provided,
backgroundColor: state.isSelected ? '#192E49' : 'inherit',
'&:hover': { backgroundColor: state.isSelected ? '#192E49' : 'rgb(222, 235, 255)' }
}),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.