reactjs 无法更改所选选项背景颜色|React选择

7rtdyuoh  于 2023-03-22  发布在  React
关注(0)|答案(5)|浏览(166)

我正在使用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"
    />
  );
}
vybvopom

vybvopom1#

为了只更改所选选项的backgroundColor,请尝试以下操作:

option: (provided, state) => ({
    ...provided,
    backgroundColor: state.isSelected ? "rgba(189,197,209,.3)" : "white",
}),
fhity93d

fhity93d2#

有一个关于这个的问题。显然isSelected只为多选提供。对于单选,您可以检查:

state.data === state.selectProps.value

https://github.com/JedWatson/react-select/issues/3817

**[Edit]**这看起来很奇怪,但如果你在组件外部声明选项,它似乎可以工作。检查here。如果你复制render函数内部的选项,那么样式将无法工作。当我尝试将值设置为“1”和“2”时,值是日期或时刻对象或其他对象时,这不是问题。
**[编辑2]**好的嗯..我重构它是一个功能组件,它与组件内的选项。我猜这可能是一个利用挂钩的问题。同样的沙箱看看。

nsc4cvqm

nsc4cvqm3#

附加到@Nathan上面的答案,如果你不想让背景颜色在悬停时改变,可以包括&hover!

option: (provided, state) => ({
  ...provided,
  backgroundColor: state.isSelected ? '#192E49' : 'inherit',
  '&:hover': { backgroundColor: state.isSelected ? '#192E49' : 'rgb(222, 235, 255)' }
}),
zpgglvta

zpgglvta4#

您可以改为利用hasValue属性
https://github.com/JedWatson/react-select/issues/3817#issuecomment-547487812

backgroundColor: state.hasValue ? "rgba(189,197,209,.3)" : "white",
lqfhib0f

lqfhib0f5#

CSS也可以
首先,您应该将前缀添加到react-select CSS类,如下所示

<Select
    classNamePrefix="an-simple-select"
    value={myValue}
    onChange={handleMyValueChange}
    options={myValueOptions}
/>

然后,您可以添加以下类到您的CSS文件,下面的代码设置选定的背景为白色,也与客户颜色颜色的悬停选项

.an-simple-select__option.an-simple-select__option--is-selected {
  background-color: white;
  color: red;
}
.an-simple-select__option:hover {
  background-color: green;
}

相关问题