如何修改React Select组件选项视图?自定义选中项样式及置顶显示
React Select 实现选中项置顶+自定义样式(不显示在输入框)
核心实现步骤
1. 隐藏输入框中的选中项
React Select默认会在输入框展示选中项,我们可以通过自定义Input组件来清空输入框的选中内容:
const CustomInput = ({ inputRef, ...props }) => { return ( <div ref={inputRef}> <input {...props} value="" placeholder={props.placeholder} /> </div> ); };
之后在Select组件中配置components={{ Input: CustomInput }}即可。
2. 将选中项置顶显示
通过对选项数组排序,把选中项移到最前面:
// 假设选中值存在selectedValue状态中 const sortedOptions = [...options].sort((a, b) => { if (a.value === selectedValue) return -1; // 选中项排前面 if (b.value === selectedValue) return 1; return 0; // 其他项保持原顺序 });
将处理后的sortedOptions传给Select的options属性。
3. 给选中项添加特殊样式
利用React Select的styles属性,针对选中的option定制样式:
const customStyles = { option: (provided, state) => ({ ...provided, backgroundColor: state.isSelected ? '#e0f7fa' : provided.backgroundColor, fontWeight: state.isSelected ? 'bold' : 'normal', color: state.isSelected ? '#00796b' : provided.color, padding: '8px 12px', borderLeft: state.isSelected ? '3px solid #00796b' : 'none' }), };
把styles={customStyles}传入Select组件即可生效。
完整示例代码
import React, { useState } from 'react'; import Select from 'react-select'; // 原始选项列表 const options = [ { value: 'option1', label: 'Option 1' }, { value: 'option2', label: 'Option 2' }, { value: 'option3', label: 'Option 3' }, { value: 'assigned', label: 'Assigned' }, ]; // 自定义输入框组件 const CustomInput = ({ inputRef, ...props }) => { return ( <div ref={inputRef}> <input {...props} value="" placeholder={props.placeholder} /> </div> ); }; // 自定义样式 const customStyles = { option: (provided, state) => ({ ...provided, backgroundColor: state.isSelected ? '#e0f7fa' : provided.backgroundColor, fontWeight: state.isSelected ? 'bold' : 'normal', color: state.isSelected ? '#00796b' : provided.color, padding: '8px 12px', borderLeft: state.isSelected ? '3px solid #00796b' : 'none' }), }; const App = () => { const [selectedValue, setSelectedValue] = useState(null); // 处理选项排序 const sortedOptions = [...options].sort((a, b) => { if (a.value === selectedValue) return -1; if (b.value === selectedValue) return 1; return 0; }); // 选中事件处理 const handleChange = (selectedOption) => { setSelectedValue(selectedOption?.value || null); }; return ( <div style={{ width: 300, margin: '20px auto' }}> <Select options={sortedOptions} value={sortedOptions.find(opt => opt.value === selectedValue)} onChange={handleChange} components={{ Input: CustomInput }} styles={customStyles} placeholder="Select an option" /> </div> ); }; export default App;
内容的提问来源于stack exchange,提问作者Rakibul Islam
相关产品推荐
相关产品推荐

