react - jsx 语法之双向绑定的单选框实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="../lib/react.js"></script> <script src="../lib/react-dom.js"></script> <script src="../lib/babel.min.js"></script> <title>react - 事件</title> </head> <body> <div id="app"> </div> <script type="text/babel"> class Radiobox extends React.Component{ constructor(){ super() this.state={ radioval:"" } // 事件性能优化 this.handleRadio = this.handleRadio.bind(this) } render(){ let radioval = this.state.radioval return ( <div className="radioBox"> <label htmlFor="sex"></label> <input type="radio" value="boy" checked={radioval === "boy"} onChange={this.handleRadio.bind(this)}/>男<br/> <input type="radio" value="girl" checked={radioval === "girl"} onChange={this.handleRadio.bind(this)}/>女<br/> <p>您选择的性别是:{radioval}</p> </div> ) } handleRadio(e){ console.log("选择性别是: ",e.target.value) this.setState({ radioval: e.target.value }) } } ReactDOM.render( <Radiobox/>, document.getElementById('app') ) </script> </body> </html>