
react select 库是开发人员创建可定制下拉组件的流行选择之一。在本文中,我们将讨论如何在 react select 中创建样式或自定义样式,以创建适合应用程序主题和 ui 设计的外观。
为什么选择 react select?
react select 可以轻松实现具有搜索、多项选择和可自定义选项等功能的灵活下拉菜单。但是,默认外观可能并不总是适合设计需求,因此我们需要添加自定义样式,以便下拉菜单与应用程序的外观融合。
在项目中使用 react select
要使用 react select,首先安装其依赖项:
npm install react-select
然后,将其导入组件并创建一个基本下拉列表:
import select from 'react-select';
const options = [
{ value: 'apple', label: 'apple' },
{ value: 'banana', label: 'banana' },
{ value: 'cherry', label: 'cherry' },
];
function myselect() {
return <select options={options} />;
}
自定义组件 react select
创建 1 个新文件,并用以下脚本填充它
import select from 'react-select'
const customselectcomponent = ({ onchange, options, value, placeholder }: any) => {
const defaultvalue = (options: any, value: any) => {
return options ? options.find((option: any) => option.value === value) : ''
}
const customstyles = {
option: (provided: any, state: { isselected: any }) => ({
...provided,
color: state.isselected ? '#ab0202' : '#000000',
background: state.isselected ? '#f4f7f9' : '#ffffff',
opacity: 1,
'&:hover': {
backgroundcolor: '#fcc2c2',
cursor: 'pointer',
},
}),
menuportal: (base: any) => ({ ...base, zindex: 9999 }),
control: (base: any, state: any) => ({
...base,
background: '#f7f7f7',
bordercolor: '#c0c4d6',
'&:hover': {
bordercolor: state.isfocused ? '#f7f7f7' : 'blue',
cursor: 'pointer',
},
}),
singlevalue: (provided: any, state: { isdisabled: any }) => {
const opacity = state.isdisabled ? 1 : 1
const transition = 'opacity 300ms'
return { ...provided, opacity, transition }
},
}
return (
<select
value={defaultvalue(options, value)}
onchange={(value) => onchange(value)}
options={options}
placeholder={placeholder}
styles={customstyles}
menuportaltarget={document.body}
/>
)
}
export default customselectcomponent
上面组件中各个prop的作用
onchange 是每次下拉选项发生更改时执行的回调函数。
options 是一个对象数组,代表下拉列表中可用的选项。
value 是当前从下拉列表中选择的值。此属性用于设置当前在下拉列表中选择的选项。
占位符是在选择选项之前作为用户指南显示的文本。此文本将显示在下拉列表中,作为选择选项的指南。
2.如何使用customselectcomponent
使用方法如下
import CustomSelectComponent from './SelectComponent'
const App = () => {
const [value, setValue] = useState('')
const options = [
{ value: 'apple', label: 'Apple' },
{ value: 'banana', label: 'Banana' },
{ value: 'cherry', label: 'Cherry' },
];
return (
<>
<CustomSelectComponent
placeholder={'Category'}
value={value}
options={options}
onChange={(value: any) => {
setValue(value.value)
}}
/>
</>)
}
export { App }
以上就是React 选择 + 自定义样式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号