[英]How to set global style for a react-select.js
我想為react-select設置全局樣式。 據我了解,我可以采取兩種方法:
使用className
和classNamePrefix
,然后使用CSS定位元素。
優點:我到處都可以使用相同的樣式
缺點:每個新組件都必須使用完全相同的className
和classNamePrefix
例:
的className =“反應選容器”
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>
使用“提供的樣式和狀態”創建外部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組件都會自動使用該樣式?
一種方法是創建自己導入的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
我不能真正確定這是否是最好的方法,但是我已經嘗試了這兩種方法,並且在一個有很多選擇的大型項目中,這是維護/修改它的最簡單方法。 此外,如果您需要自定義組件,這真的很方便。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.