react单选框获取值

react的input的每一种类型都要绑定onChange事件的,绑定onChange事件要传入事件对象的

react的单选框需要绑定checked属性的

import React, { Component } from 'react'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      sex:"0" // 定义选中的值,如果为空字符串,则默认不选中
     }
  }
  render() { 
    return (
        <div>
          <input type="radio" name="" value="0" checked={this.state.sex==0} onChange={(e)=>this.getValue(e)}/><label htmlFor="man">男</label>
          <input type="radio" name="" value="1" checked={this.state.sex==1} onChange={(e)=>this.getValue(e)}/><label htmlFor="woman">女</label>
        </div>
      );
  }
  getValue=(event)=>{
    //获取单选框选中的值
    console.log(event.target.value);
    this.setState({
      sex:event.target.value
    })
  }
}
 
export default App;

猜你喜欢

转载自www.cnblogs.com/luguankun/p/11161835.html