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

How to set global style for a react-select.js

我想为 react-select 设置全局样式。据我了解,我可以采用两种方式:

  1. 使用 classNameclassNamePrefix,然后使用 CSS.

    定位元素

    优点:我可以在任何地方使用相同的样式

    缺点: 每个新组件必须使用完全相同的 classNameclassNamePrefix

示例:

className='react-select-container'

classNamePrefix="react-select"

结果:

<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. 使用 "Provided Styles and State"

    创建外部 javascript 文件

    优点:比CSS

    更灵活

    缺点: 每个新组件都必须使用导入的外部文件的样式 属性。

示例:

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 组件自动使用该样式吗?

一种方法是创建您自己的 select 组件,例如您导入的 CustomSelect 而不是 react-select,您在其中设置自定义 styletheme 喜欢:

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

我真的不能说这是否是最好的方法,但我已经尝试过这两种方法,并且在一个有很多 select 的大项目中,这是维护/修改它的最简单方法。另外,如果在某些时候您需要自定义组件,这真的很方便。