【问题标题】:not able to get choice group target id to set values dynamically无法获取选择组目标 ID 以动态设置值
【发布时间】:2021-11-09 05:49:47
【问题描述】:

这是我的选择组元素

 <ChoiceGroup defaultSelectedKey="No"
  options={[{ key: 'Yes', text: 'Yes' },{ key: 'No', text: 'No' }]}
  onChange={this._onChange}
  id={'ChoiceGroup1'}
  name={this.state.currentUser} />

还有我的 onChange 函数

public _onChange=(ev, option: IChoiceGroupOption)=> {
console.log(ev,option); } 

但我无法获得 target.id 值。目标显示为空,但在 Textfield 的情况下,我能够获取组件的名称和目标

【问题讨论】:

  • 可以分享相关的ChoiceGroup组件代码吗?

标签: javascript html reactjs office-ui-fabric


【解决方案1】:

您可以手动将所选项目的 id 传递给 _onChange 函数。

根据道具和用例,我假设您的 ChoiceGroup 组件通过“选项”道具映射并呈现另一个组件。如果是这种情况,您可以稍微调整一下,使其将点击的项目传递给父组件(这样您就可以决定如何处理它)。

所以在你的 ChoiceGroup 组件中添加

{options.map(option =>
<ChoiceGroupOption
  onClick={e => onItemSelected(option)}
/>}

 <ChoiceGroup defaultSelectedKey="No"
   options={[{ key: 'Yes', text: 'Yes' },{ key: 'No', text: 'No' }]}
   onItemSelected={item => this._onChange(e, item.id)}
   id={'ChoiceGroup1'}
   name={this.state.currentUser} />

然后在事件处理程序中输入:

public _onChange = (ev, selectedId)=> {
    console.log('ID: ', selectedId);
}

【讨论】:

  • 这段代码中的selectedId 是什么?我的猜测是ChoiceGroup 组件将选定的选项传递给处理程序,所以这个解决方案看起来像是放弃了它并将一个未定义的值传递给this._onChange 处理程序。
  • 我假设他在某处有一个显示项目的地图,在这种情况下,可以轻松地将 id 作为参数传递给函数。 ChoiceGroup 肯定是一个自定义组件,因为没有这样的 html 标签。
  • 这是一个相当的假设,仍然无法解释 selectedId 的来源。
  • @DrewReese 我编辑了我的答案以进一步解释。
猜你喜欢
  • 2015-08-08
  • 2014-10-18
  • 1970-01-01
  • 2021-06-16
  • 2014-08-28
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 2020-08-17
相关资源
最近更新 更多