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 ;}
登录后复制
定制风格
自定义组件 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 ( 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 ( { setValue(value.value) }} /> 登录后复制以上就是React 选择 + 自定义样式的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2655416.html