最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change react-select options styles when select - Stack Overflow

programmeradmin6浏览0评论

I am using react-select latest to create an async select ponent. I am trying to change the background color and border color of the select, once I select some value. I went through the document and tried using state.isSelected to conditionally change the background color. But no help.

When the value is selected as below, I would like to change the background color and also the border color. But nothing seems to happen. Help would be appreciated

I am using react-select latest to create an async select ponent. I am trying to change the background color and border color of the select, once I select some value. I went through the document and tried using state.isSelected to conditionally change the background color. But no help.

When the value is selected as below, I would like to change the background color and also the border color. But nothing seems to happen. Help would be appreciated

Share Improve this question edited Mar 22, 2020 at 15:02 keikai 15.2k10 gold badges55 silver badges72 bronze badges asked Mar 22, 2020 at 11:24 Brijesh PrasadBrijesh Prasad 5798 silver badges25 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

Method

Refer to document: react-select customize styles

You can override the default provided styles in different domains.

In this case, the base control would be good enough.

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

Demo


Source

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;

发布评论

评论列表(0)

  1. 暂无评论