首页 > 解决方案 > 有没有办法在保持大部分原始风格的同时对反应选择进行风格化?

问题描述

我正在使用https://react-select.com/home#getting-started并且我正在尝试创建尽可能接近此的内容:在此处输入图像描述

我编码的原始选择样式(没有选择库中的customStyles函数)给了我这样的东西:

在此处输入图像描述

但是一旦我开始添加样式选择库中的customStyles函数),如下所示:

import { useEffect, useState } from 'react';
// styled components
import styled from 'styled-components';
// icons
import { IoIosArrowDown } from 'react-icons/io';
// select input
import Select from 'react-select';

const ContextItem = ({ text, options }) => {
  const [treeNodeNames, setTreeNodeNames] = useState();

// THIS IS FROM THE LIBRARY
const customStyles = {
  option: (provided, state) => ({
    ...provided,
    // borderBottom: '1px dotted pink',
    color: state.isSelected ? 'white' : 'black',

  }),
  control: () => ({
    // none of react-select's styles are passed to <Control />
    width: 200,
  }),
  singleValue: (provided, state) => {
    const opacity = state.isDisabled ? 0.5 : 1;
    const transition = 'opacity 300ms';

    return { ...provided, opacity, transition };
  },
};
  useEffect(() => {
    if (options) {
      const treeNodes = options.data.findTreeNodesByTree.map((element) => {
        return {value: element.name, label: element.name  };
      });

      setTreeNodeNames(treeNodes);
    }
  }, [options]);

  return (
    <ContextContainer>
      <ContextTitle>
        <p> {text}</p>
      </ContextTitle>
      {treeNodeNames && (
        <SearchInput>
          <Select options={treeNodeNames} styles={customStyles} />
        </SearchInput>
      )}
    </ContextContainer>
  );
};

// STYLES
const ContextContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
`;

const ContextTitle = styled.div`
  display: flex;
  width: 30%;
  align-items: center;
  justify-content: space-between;
`;
const SearchInput = styled.div`
  width: 60%;
  padding: 5px;
  outline: black;
`;

export default ContextItem;

我得到这样的东西:

在此处输入图像描述

所以问题是:如何在不破坏所有内容的情况下使用 select中的customStyles实现第一张照片中显示的预期结果?有没有办法将原始反应选择的样式传递给并相应地修改它们。最后我只需要:

我希望有道理,如果问题不清楚,请告诉我:) 我感谢任何形式的帮助和线索。

标签: cssreactjs

解决方案


这个react-select组件由多个较小的部分组成。

您在正确的轨道上应用自定义样式。这是您可以自定义的 react-select 的各个部分的列表。语法:

const customStyles = {
  option: (provided, state) => ({
    ...provided,
    color: state.isSelected ? 'red' : 'blue',
    // rest of styling
  })
}

例如,如果您想更改没有可用选项的文本,您将设置noOptionsMessage的样式。

其他需要注意的事项:

  1. 要访问类似于选项:hover组件的伪类,CSS-in-JS 使用以下语法:."&:hover": {...}
  2. 有关如何在此处检查组件的伪状态和设置样式的更多详细信息。

这是一个代码框,它的 react-select 样式接近您的第一张图片。


推荐阅读