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

时间:2017-10-13 11:37:06

标签: reactjs radio-button

如果我在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 个答案:

答案 0 :(得分:3)

根据此lib的DOCSRadioGroup有一个onChange道具处理程序,您可以传递它将返回所选值,然后您可以将其设置为状态或传递它。

以下是您的代码的小型运行示例:

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>

答案 1 :(得分:3)

来自this react-radio-buttons example

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 :(得分:2)

将onChange事件添加到RadioGroup。

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