2017-10-13 118 views
3

如何獲取單選按鈕的值,如果我在RadioGroup中調用updateRadioButton,則會導致錯誤。我需要在控制檯中使用(react-radio-buttons)作爲男性或女性進行打印。單選按鈕打印正確,但我無法獲得價值。先謝謝你。如何獲取Reactjs中的單選按鈕(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

那麼根據這個LIB的DOCSRadioGrouponChange道具處理程序,你可以通過將返回所選擇的值,然後你可以將其設置在該州或通過它。

這裏是小運行你的代碼示例:

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/[email protected]/build/bundle.min.js"></script> 
 
<div id="root"></div>

+0

謝謝@ Sag1v – PremKumar

+0

@PremKumar沒有問題,iv'e增加了運行的片段與您的代碼 –

+0

哇,太謝謝你了:-) – PremKumar

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> 
    ) 
    ... 
    } 
} 
+0

謝謝Firice,這是很酷:-) – PremKumar

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

謝謝。 但是,e.target.value不起作用。 updateRadioButton(value){ this.setState({radio:value}) } – PremKumar

+0

你是對的。我沒有注意到。我剛剛更新。 –

相關問題