选择时如何更改反应选择选项样式

时间:2020-03-22 11:24:44

标签: javascript html css reactjs react-select

我正在使用react-select Latest创建一个异步选择组件。一旦选择一些值,我将尝试更改选择的背景色和边框色。我浏览了文档,并尝试使用 state.isSelected 有条件地更改背景颜色。但是没有帮助。

When no value is selected

按如下所示选择值时,我想更改背景颜色以及边框颜色。但是似乎什么也没发生。帮助将不胜感激

enter image description here

1 个答案:

答案 0 :(得分:2)

方法

参考文档:反应选择customize styles

您可以覆盖不同域中提供的默认样式。

在这种情况下,基本的控件就足够了。

const customStyles = stateValue => ({
  control: (provided, state) => ({
    ...provided,
    backgroundColor: stateValue ? "gray" : "white"
  })
});

演示

enter image description here


来源

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;

Edit cocky-worker-h2sgn

相关问题