gab*_*iso 2 reactjs react-select styled-components
我使用的是反应选择库中的选择元素,在我的项目中我使用的是样式组件。我想问我是否可以在 styles.ts 文件中对其进行样式设置。如果不可能,你们能给我一些如何做造型的建议吗?
React 内部:FC
import Select from 'react-select'
...
const options = [
{ value: 'Income', label: 'Income' },
{ value: 'Expense', label: 'Expense' },
]
...
<Form>
<InputElement />
<Select options={options} />
</Form>
Run Code Online (Sandbox Code Playgroud)
是的,可以提供您自己的自定义样式,react-select提供基于对象的方法来设置Select组件的样式。
参考文档
这是一个简单的例子,
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} // pass the customStyles object to the styles prop
options={...}
/>
);
Run Code Online (Sandbox Code Playgroud)
通过提供给自定义样式对象的键,选择是可以高度自定义的。
要记住的一件事是,每个键将是一个样式函数,其中第一个参数将是提供的样式,第二个参数将是 select 的状态,即isFocused, isSelected。
编辑- 虽然这是使用基于对象的方法提供自定义样式的建议方法。如果您确实想使用 来设置Select组件的样式styled-components,这里有一个示例(您必须提供一个classNamePrefixthrough 属性和基于 classNames 的样式)
有关使用 classNames文档进行样式设置的更多详细信息
import Select from 'react-select';
import styled from 'styled-components';
const SelectElement = styled(Select)`
.react-select-container {
// custom styles
}
.react-select__control {
// custom styles
}
.react-select__indicators {
// custom styles
}
`;
const MySelect = (props) => {
return (
<SelectElement classNamePrefix="react-select" options={options} {...props}/>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15006 次 |
| 最近记录: |