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;
循环input选项的写法:
import React, { Component } from 'react' class App extends Component { constructor(props) { super(props); this.state = { items: ["星期一", "星期二", "星期三"], item: "1" } } render() { return ( <div> { this.state.items.map((ele, index) => { return ( <p key={index}> {/* 如果控制台有警告 Expected '===' and instead saw '==' eqeqeq 不用改成三个等号 */} <input type="radio" name="group" value={index} checked={this.state.item == index} onChange={(e) => this.getValue(e)} /><span>{ele}</span> </p> ) }) } </div> ); } getValue = (e) => { this.setState({ item: e.target.value }) } } export default App;