如何在Reactjs中获取单选按钮(react-radio-buttons)的值?

4

如何获取单选按钮的值,如果我在RadioGroup中调用updateRadioButton,则会出现错误。我需要使用(react-radio-buttons)在控制台中打印为男性或女性。单选按钮正确地打印,但我无法获取值。提前致谢。

 class CreateUserComponent extends React.Component {
        constructor(props) {
        super(props); 
        this.state={radio:''}
    }

    updateRadioButton(e) {
        this.setState({ radio: e.target.value });
    }

    <RadioGroup horizontal>
            <RadioButton value="Male">Male</RadioButton>
            <RadioButton value="Female">Female</RadioButton>
        </RadioGroup>
3个回答

4
根据这个库的文档RadioGroup有一个onChange属性处理程序,您可以传递它来返回所选值,然后您可以将其设置在状态中或传递它。请注意保留HTML标记。

Here is small running example with your code:

debugger
const RadioGroup = ReactRadioButtonsGroup.ReactRadioButtonsGroup;
const RadioButton = ReactRadioButtonsGroup.ReactRadioButton;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  onRadiochange = value => {
    console.log(value);
  };

  render() {
    return (
      <div>
        <RadioGroup horizontal onChange={this.onRadiochange}>
          <RadioButton value="Male">Male</RadioButton>
          <RadioButton value="Female">Female</RadioButton>
        </RadioGroup>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-radio-buttons-group@1.0.2/build/bundle.min.js"></script>
<div id="root"></div>


@PremKumar 没问题,我已经添加了一个运行代码片段。 - Sagiv b.g
哇,非常感谢 :-) - PremKumar

3

以下内容来自这个react-radio-buttons的例子

class CreateUserComponent extends React.Component {
  ... 
  updateRadioButton(value) {
    this.setState({ radio: value });
  }

  render() {
    ...

    return (
      <RadioGroup horizontal onChange={this.updateRadioButton} >
        <RadioButton value="Male">Male</RadioButton>
        <RadioButton value="Female">Female</RadioButton>
      </RadioGroup>
    )
    ...
  }
}

2

在RadioGroup中添加onChange事件。

class CreateUserComponent extends React.Component {
    constructor(props) {
    super(props); 
    this.state={radio:''};
    this.updateRadioButton = this.updateRadioButton.bind(this);
}

updateRadioButton(value) {
    this.setState({ radio: value });
}

render() {
 return(
   <RadioGroup horizontal onChange={this.updateRadioButton}>
        <RadioButton value="Male">Male</RadioButton>
        <RadioButton value="Female">Female</RadioButton>
   </RadioGroup>
 );
}

谢谢。但是,e.target.value不起作用。updateRadioButton(value) { this.setState({ radio: value }) } - PremKumar
您是正确的。我没有注意到那个。我现在已经更新了。 - user-developer

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