fluentui/react-northstar的Dropdown组件onChange无法获取选中值如何解决
Fluent UI Northstar Dropdown onChange 获取选中值解决方案
Fluent UI Northstar 的 Dropdown 组件onChange回调设计为接收两个参数:第一个是原生事件对象e,部分场景下该对象会被事件池回收置为 null;第二个是组件返回的元数据对象,选中值存放在该对象中。
解决步骤
- 修改 Dropdown 组件的 onChange 传参,新增第二个参数传递组件元数据
- 在自定义处理函数中接收第二个参数,从其
value属性获取选中值
修改后的完整代码如下:
import React from "react"; import { Flex, Header, Dropdown } from '@fluentui/react-northstar'; class DropdownComponent extends React.Component { constructor(props) { super(props); this.state = { inputItems: [ 'Robert Tolbert', 'Wanda Howard', 'Tim Deboer', 'Amanda Brady', 'Ashley McCarthy', 'Cameron Evans', 'Carlos Slattery', 'Carole Poland', 'Robin Counts', ], selectedValue: [] // 可选:新增state存储选中值,实现受控组件 } this.onChangeHandler = this.onChangeHandler.bind(this); } // 新增第二个参数接收组件返回的元数据 onChangeHandler(e, data){ // checkable多选模式下value为选中项的数组,非多选模式为单个选中值 const selectedValue = data.value; console.log('当前选中值:', selectedValue); // 可选:将选中值写入state this.setState({ selectedValue }) } render() { return ( <section> <Flex column gap="gap.small"> <Header as="h4" content="Object" /> <Dropdown items={this.state.inputItems} placeholder="Select your object" checkable value={this.state.selectedValue} // 可选:绑定选中值实现受控组件 // onChange新增第二个参数传递元数据 onChange={(e, data) => this.onChangeHandler(e, data)} /> </Flex> </section> ); } } export default DropdownComponent;
补充说明
如果你的 Dropdown 没有开启checkable多选模式,data.value返回的就是单个选中的字符串值,无需处理数组格式。
内容的提问来源于stack exchange,提问作者Titus Annadurai
相关产品推荐
相关产品推荐

