React-Bootstrap-Typeahead实现嵌套下拉选项的方案问询
实现方案
react-bootstrap-typeahead 原生未内置嵌套下拉能力,可通过状态控制子选项显隐+自定义选项渲染的方式实现需求,具体实现如下:
步骤1:新增状态管理父级激活状态
import { useState } from 'react'; import Typeahead from 'react-bootstrap-typeahead'; const options = [ { value: 'one', }, { value: 'two', }, { value: 'three', extraOptions: [ // 给子选项加标记方便渲染时区分层级 { value: 'three point one', isChild: true }, { value: 'three point two', isChild: true }, ], } ]; function YourComponent() { // 记录当前选中的带嵌套选项的父级 const [activeParent, setActiveParent] = useState(null); // 动态生成最终渲染的下拉选项 const finalOptions = [...options]; if (activeParent) { finalOptions.push(...activeParent.extraOptions); }
步骤2:改造Typeahead组件配置
return ( <Typeahead multiple type='text' onChange={(selected) => { const latestSelect = selected[selected.length - 1]; // 选中带extraOptions的父级时,激活子选项显示 if (latestSelect?.extraOptions) { setActiveParent(latestSelect); } // 取消父级选中时,隐藏子选项 if (activeParent && !selected.some(item => item.value === activeParent.value)) { setActiveParent(null); } handleChange(selected); }} options={finalOptions} labelKey='value' // 自定义选项渲染,子选项加缩进区分层级 renderMenuItemChildren={(option) => ( <div style={{ paddingLeft: option.isChild ? '20px' : 0 }}> {option.value} </div> )} /> ) }
可选调整
如果需要选中父级后,仅展示对应的子选项,修改finalOptions的计算逻辑即可:
const finalOptions = activeParent ? activeParent.extraOptions : options;
内容的提问来源于stack exchange,提问作者8245734589
相关产品推荐
相关产品推荐

