如何在React中获取多个单选按钮组中的所选值?

4

我有一组类似这样的单选按钮:

return committees.map((committee) => {
  return (
    <div>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="1" />
      <label>1</label>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="2" />
      <label>1</label>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="3" />
      <label>1</label>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="4" />
      <label>1</label>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="5" />
      <label>1</label>
    </div>
  );
});

这个页面有多个类似的组。React ref并不能给我正确的值。它对所有组都返回最后一个值5。如果我使用getElementsByName,它会给我返回5个元素(5个单选按钮字段)。我需要获取所选组的值。我该怎么做?

2个回答

3
您可以使用一个映射表来保留内部状态,将委员会的简称与选定的值相对应(在onChange事件中更新状态),然后添加以下内容:
checked={this.state.selectedValues[committee.shortName] === radioValue}

这里有一个示例:单选按钮示例

还有一个库可以为您提供更简洁的代码:react-radio-group


非常感谢!我使用了 react-radio-group 插件,它很好用。但有一件小事,您直接将一个值分配给了状态 this.state.selectedValues[committee.shortName] === radioValue。我们应该使用 setState 是吗? - THpubs
很高兴听到这个消息!这不是一个任务,而是一种比较。你可以查看这个fiddle,看看它是如何工作的。 - omerts
非常抱歉,是我的错误!谢谢 :-) - THpubs
太棒了!感谢你提供的示例代码! - fungusanthrax

0

如果你正在使用React,我认为以jQuery的方式使用它并不正确,使用ref - React作为一个最终状态机运行良好,你应该将组件数据存储在state中,而不是通过ref访问组件来请求它。

因此,你应该添加类似于onChange= ()=>this.setState({selectedValue: 'yourValue'})的内容,以正确传递更改后的值到状态中,如果你想使用“受控”输入,则使用value={this.state.selectedValue}或在单选按钮的情况下使用checked={this.state.selectedValue === 'yourValue'}

但实际上你不需要使用react来进行单选框和组的选择,你可以做一些像这样的事情:

committies.map(committie => (
  <button className={this.state.selectedValue === committie.id ? 'selected' : ''}
          onClick={() => this.setState({selectedValue: committie.id})}>
      {committee.shortName}
  </button>
))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接