React-Select 为选中选项添加自定义类实现复选框选中样式
问题描述
在React-Select组件中实现选项行内复选框的选中联动效果时,需要对选中选项的::after伪元素做差异化样式调整。当前已可通过SCSS修改组件全局样式,但组件生成的选项类名带有随机后缀,格式为css-[random]-option,无法精准区分选中、未选中的选项,导致没法给选中态设置对应的复选框勾选样式。
目前已完成基础页面结构搭建,仅差复选框的勾选状态样式未实现,现有代码如下:
现有JSX实现
const customStyles = {} return( <div class="SelectContainer"> <div class="opener" onClick={(e) => {setIsOpen(!isOpen);}}> {outputValue ? outputValue : placeholder} <Chevron /> </div> {isOpen && <Select onChange={onChangeFunction} value={elementValue} autoFocus backspaceRemovesValue={false} controlShouldRenderValue={false} hideSelectedOptions={false} menuIsOpen tabSelectsValue={false} noOptionsMessage={()=>{return "Aucun résultat";}} placeholder="Rechercher" customStyles={customStyles} {...rest} //style={{width:"100%"}} > {choices && choices.map((choice) => { return (<option key={choice.val} value={choice.val}>{choice.option}</option>) })} </Select> } </div> )
现有SCSS实现
.SelectContainer{ .opener{ display:flex; align-items: center; justify-content: space-between; padding:0 24px; height:72px; //border:1px solid #000; background:#fff; } input{ height:24px; } [class$="container"]{ background:#fff; //padding:0 24px; padding:0; [class$="ValueContainer"]{ } [class$="control"]{ border:0; position:relative; padding-left:30px; margin:0 24px; &:before{ content:' '; display:block; position:absolute; top:50%; left:0; transform:translateX(-0) translateY(-50%); width:16px; height:16px; background:url(../../assets/image/search.svg) center center no-repeat; background-size:contain; } [class$="Input"]{ width: calc(100% - 50px); z-index: 100; position: relative; input{width:100% !important;} } } [class$="IndicatorsContainer"] [class$="indicatorContainer"]:last-child,[class$="IndicatorsContainer"] [class$="indicatorSeparator"]{ display:none !important; } [class$="indicatorContainer"]{ padding:0; } [class$="menu"]{ position:relative; box-shadow:none; [class$="option"]{ background:none !important; color:#000 !important; position:relative; padding:8px 24px; cursor:pointer; &:hover{ background:var(--light) !important; } &:after{ width:16px;height:16px; display:block;position:absolute; content:' '; border:2px solid #000; position:absolute; right:24px; top:calc(50% - 8px); } } } } }
解决方案
可以通过React-Select本身提供的状态入参能力,主动为选中选项追加自定义类名,无需依赖组件自动生成的随机类名做匹配,常用实现方式如下:
方式1:自定义Option渲染组件,为选中态追加专属类名
React-Select的自定义Option组件会接收isSelected状态参数,可在渲染DOM时根据选中状态拼接类名:
// 自定义选项渲染组件 const CustomSelectOption = (props) => { const { data, isSelected, innerRef, innerProps, children } = props; return ( <div ref={innerRef} {...innerProps} // 选中时追加自定义选中类名 className={`custom-option-base ${isSelected ? 'custom-option-selected' : ''}`} > {children} </div> ) } // 替换原有Select的配置 <Select // 保留原有所有props components={{ Option: CustomSelectOption }} options={choices.map(item => ({ value: item.val, label: item.option }))} />
配置完成后,可直接在SCSS中针对.custom-option-selected::after写选中态样式,比如替换原有的空心方框为勾选图标:
// 在原有SCSS基础上追加 [class$="menu"] { .custom-option-selected::after { border: none; background: url(本地勾选图标路径) center / contain no-repeat; } }
方式2:通过已配置的customStyles动态设置选中态样式
不需要额外写类名规则,直接在已定义的customStyles对象中,利用Option样式回调拿到的state.isSelected参数,动态设置伪元素样式:
const customStyles = { option: (baseStyle, state) => ({ ...baseStyle, // 保持原有未选中态的伪元素样式 '::after': { content: ' ', width: '16px', height: '16px', position: 'absolute', right: '24px', top: 'calc(50% - 8px)', border: '2px solid #000', // 选中态时替换为勾选样式 ...(state.isSelected ? { border: 'none', background: `url(本地勾选图标路径) center / contain no-repeat` } : {}) } }) }
内容的提问来源于stack exchange,提问作者Fredy31
相关产品推荐
相关产品推荐

