react-bootstrap-typeahead单选模式下selected传数组触发警告问题排查
react-bootstrap-typeahead 单选模式下
selected属性警告解决 触发的警告信息
Warning: [react-bootstrap-typeahead] You are passing multiple options to the
selectedprop of a Typeahead in single-select mode. This may lead to unexpected behaviors or errors.
问题场景
使用react-bootstrap-typeahead时触发上述警告,已按要求将selected属性传入Option[]数组类型,但警告仍存在,代码如下:
const [selected, setSelected] = useState<Option[]>([]); const options = ["option1", "option2"]; const handleChange = (opt: Option[]) => { setSelected(opt); }; <Typeahead onChange={handleChange} options={options} selected={selected} />
问题原因
react-bootstrap-typeahead默认是单选择模式,此模式下即使selected是数组类型,也只能包含0个或1个元素。如果selected数组存在多个元素,就会触发该警告。
解决方案
场景1:需要单选功能
确保selected数组始终只保留0个或1个元素,修改handleChange方法:
const handleChange = (opt: Option[]) => { // 只保留第一个选中项,保证数组长度不超过1 setSelected(opt.slice(0, 1)); };
场景2:需要多选功能
给Typeahead组件添加multiple属性,开启多选模式,此时组件允许selected数组包含多个元素:
<Typeahead onChange={handleChange} options={options} selected={selected} multiple />
内容的提问来源于stack exchange,提问作者Adrian Golda
相关产品推荐
相关产品推荐

