选择时如何更改反应选择选项样式 [英] How to change react-select options styles when select

查看:34
本文介绍了选择时如何更改反应选择选项样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

当值选择如下,我想更改背景颜色和边框颜色.但似乎什么都没有发生.帮助将不胜感激

解决方案

方法

参考文档:react-select

<小时>

来源

import React, { useState } from "react";导入从反应选择"中选择;常量选项 = [{ 值:巧克力",标签:巧克力"},{值:草莓",标签:草莓"},{ 值:香草",标签:香草"}];const customStyles = value =>({控制:(提供,状态)=>({...假如,alignItems: "基线",背景颜色:值?灰色":白色"})});const App = () =>{const [selected, setSelected] = useState("");const onChange = e =>{setSelected(e.value);};const onClickButton = () =>{setSelected("");};const displayItem = 选择 =>{const item = options.find(x => x.value === selected);归还物品 ?项目:{值:",标签:"};};返回 (<><选择选项={选项}样式={customStyles(selected)}onChange={onChange}值={displayItem(selected)}/><button onClick={onClickButton}>清除选择</button></>);};导出默认应用程序;

I am using react-select latest to create an async select component. 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

解决方案

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;

这篇关于选择时如何更改反应选择选项样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆