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

时间:2016-05-29 15:45:42

标签: reactjs

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

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>
  );
});

此页面中有多个这样的组。反应ref没有给我正确的价值。它为所有组提供值5(最后一个值)。如果我使用getElementsByName,它会给我5个元素(5个单选按钮字段)。我需要获取该组的选定值。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

您可以使用commitee.shortName =&gt;之间的地图保持内部状态。 selectedValue(更新状态onChange),然后添加:

checked={this.state.selectedValues[committee.shortName] === radioValue}

这是一个小提琴:Radio Buttons Example

还有一个图书馆为您解雇: react-radio-group

答案 1 :(得分:0)

如果你正在使用React我不认为使用jQuery风格的正确方法,使用state - React作为最终状态机很好用,你应该存储您的组件数据位于ref,请勿按onChange= ()=>this.setState({selectedValue: 'yourValue'})请求访问组件。

因此,您应该添加value={this.state.selectedValue}之类的内容,以便将正确更改的值传递给状态,如果您想使用&#34;控制&#34;输入checked={this.state.selectedValue === 'yourValue'}或使用单选按钮committies.map(committie => ( <button className={this.state.selectedValue === committie.id ? 'selected' : ''} onClick={() => this.setState({selectedValue: committie.id})}> {committee.shortName} </button> ))

但你真的不需要使用无线电检查和反应组,你可以这样做:

=>
相关问题