代码之家  ›  专栏  ›  技术社区  ›  Observer

如何为react-select.js设置全局样式

  •  1
  • Observer  · 技术社区  · 6 年前

    react-select . 据我所知,我可以采取两种方式:

    1. 使用 className classNamePrefix 然后使用CSS将元素作为目标。

      赞成的意见: 我可以在任何地方使用相同的样式

      欺骗: 类名 类名前缀

    例子:

    classNamePrefix=“反应选择”

    结果:

    <div class="react-select-container">
      <div class="react-select__control">
        <div class="react-select__value-container">...</div>
        <div class="react-select__indicators">...</div>
      </div>
      <div class="react-select__menu">
        <div class="react-select__menu-list">
          <div class="react-select__option">...</div>
        </div>
      </div>
    </div>
    
    1. 使用创建外部javascript文件 "Provided Styles and State"

      赞成的意见:

      欺骗: 每个新组件都必须使用导入的外部文件使用样式特性。

    例子:

    const customStyles = {
      option: (provided, state) => ({
        ...provided,
        borderBottom: '1px dotted pink',
        color: state.isSelected ? 'red' : 'blue',
        padding: 20,
      }),
      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 };
      }
    }
    
      const App = () => (
        <Select
          styles={customStyles}
          options={...}
        />
      );
    

    设置多个react select组件样式的最佳方法是什么?是否可以全局设置样式,并且每个新的react select组件都会自动使用该样式?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Laura    6 年前

    一种方法是创建自己的选择组件,如 CustomSelect react-select 您在其中设置了一个自定义 style theme 比如:

    import React, { Component } from 'react'
    import Select from 'react-select'
    
    class CustomSelect extends Component {
      render() {
    
        const styles = {
          ...
          // what ever you need
        }
    
        return <Select styles={styles} {...this.props} />
      }
    }
    
    export default CustomSelect
    

    我真的不知道这是否是最好的方法,但我已经尝试了这两种方法,并且在一个有很多人选择的大型项目中,这是维护/修改它的最简单的方法。另外,如果在某个时候需要自定义组件,那么它非常方便。