1. 程式人生 > >react表單的一些小例子

react表單的一些小例子

<!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"> <title>Document</title> <script src="../node_modules/react/umd/react.development.js"></script> <script src="../node_modules/react-dom/umd/react-dom.development.js"></script> <script src="../node_modules/babel-standalone/babel.min.js"></script> </head> <body> <div id="my"></div> <script type="text/babel"> class FormGroup extends React.Component{ constructor(props){ super(props) this.state = { name:'', psd:'', sex:'man', city:'2', } } handleChange(e){ let name = e.target.name; this.setState({ [name]:e.target.value }) };   submit(){ let data={ userName:this.state.name, userPassWord:this.state.psd, userSex:this.state.sex, userCity:this.state.city } alert(JSON.stringify(data)) } render(){ let cityArr=[ {name:'北京'}, {name:'上海'}, {name:'廣州'}, ] return( <div> <label>姓名:</label> <input name="name" type="text" value={this.state.name} onChange={(e)=>this.handleChange(e)}/> {this.state.name} <label>密碼:</label> <input name="psd" type="password" value={this.state.psd} onChange={(e)=>this.handleChange(e)}/> {this.state.psd} <input type="radio" name="sex" checked={this.state.sex=='man' ? true :false} value="man" onChange={(e)=>this.handleChange(e)}/>男 <input type="radio" name="sex" checked={this.state.sex=='woman' ? true :false} value="woman" onChange={(e)=>this.handleChange(e)}/>女 <label>城市:</label> <select name="city" value={this.state.city} onChange={(e)=>this.handleChange(e)}> { cityArr.map((val,index)=>{ return <option key={index} value={index+1}>{val.name}</option> }) } </select> <button onClick={()=>this.submit()}>提交</button> </div> ) } } ReactDOM.render( <div> <FormGroup/> </div>, document.getElementById('my') ) </script> </body> </html>