当前位置 : 主页 > 网页制作 > React >

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

来源:互联网 收集:自由互联 发布时间:2021-06-15
我有一组像这样的单选按钮: return committees.map((committee) = { return ( div input type="radio" name={committee.shortName} ref={`${committee.shortName}Preference`} defaultChecked="true" value="1" / label1/label input type="rad
我有一组像这样的单选按钮:

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个单选按钮字段).我需要获取该组的选定值.我怎样才能做到这一点?

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

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

这是一个小提琴:Radio Buttons Example

还有一个图书馆可供您使用:
react-radio-group

网友评论