React ChoiceGroup组件onChange事件无法获取target.id问题问询
问题原因
Fluent UI(原Office UI Fabric)的ChoiceGroup属于复合组件,和结构简单的TextField不同:
- 你给
ChoiceGroup设置的id、name属性是挂载在组件最外层容器DOM上的,而onChange触发的原生事件来自组件内部的单选按钮元素,事件默认指向内部单选按钮,不会携带外层容器的属性 - 框架的合成事件回收机制也会导致你读取
ev.target时得到null
解决方法
通过闭包直接把你需要的id、name参数传给_onChange回调即可,完全不用依赖事件对象的target属性,稳定性最高,写法如下:
修改ChoiceGroup组件调用
<ChoiceGroup defaultSelectedKey="No" options={[{ key: 'Yes', text: 'Yes' },{ key: 'No', text: 'No' }]} onChange={(ev, option) => this._onChange(ev, option, 'ChoiceGroup1', this.state.currentUser)} id={'ChoiceGroup1'} name={this.state.currentUser} />
修改_onChange函数定义
public _onChange = (ev, option: IChoiceGroupOption, groupId: string, groupName: string) => { // 直接拿到你需要的分组ID、name和选中的选项 console.log('ChoiceGroup的id:', groupId); console.log('ChoiceGroup的name:', groupName); console.log('当前选中的选项:', option); }
如果是动态渲染多个ChoiceGroup的场景,这种写法同样适用,循环渲染时把每个分组对应的id、name参数传入回调即可。
内容的提问来源于stack exchange,提问作者Pavan Kalyan
相关产品推荐
相关产品推荐

