[英]How to set global style for a react-select.js
I would like to set global style for the react-select . 我想为react-select设置全局样式。 For my understanding I can do 2 ways:
据我了解,我可以采取两种方法:
Using className
and classNamePrefix
and then target elements using CSS. 使用
className
和classNamePrefix
,然后使用CSS定位元素。
PROS: I can use the same style everywhere 优点:我到处都可以使用相同的样式
CONS: Every new component must use exactly the same className
and classNamePrefix
缺点:每个新组件都必须使用完全相同的
className
和classNamePrefix
Example: 例:
className='react-select-container'
的className =“反应选容器”
classNamePrefix="react-select"
classNamePrefix = “反应-选择”
Result: 结果:
<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>
Create external javascript file with "Provided Styles and State" 使用“提供的样式和状态”创建外部javascript文件
PROS: more flexible then CSS 优点:比CSS更灵活
CONS: Every new component must use style property using imported external file. 缺点:每个新组件都必须通过导入的外部文件使用样式属性。
Example: 例:
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={...} /> );
What is the best way to style multiple react-select components? 设置多个反应选择组件的最佳方法是什么? Will be possible to set style globally and every new react-select component use that style automatically?
是否可以全局设置样式,并且每个新的react-select组件都会自动使用该样式?
One way to do it is to create your own select component like CustomSelect
that you import instead of react-select
where you set for one the custom style
or theme
like: 一种方法是创建自己导入的Select组件(如
CustomSelect
,而不是对其中一种自定义style
或theme
设置的react-select
:
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
I can't really tell if it's the best way or not but I've tried both of it and in a big project with many select it's the easiest way to maintain / modify it. 我不能真正确定这是否是最好的方法,但是我已经尝试了这两种方法,并且在一个有很多选择的大型项目中,这是维护/修改它的最简单方法。 Plus it's really convenient if at some point you need to have custom components.
此外,如果您需要自定义组件,这真的很方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.