React 學習筆記 (三)(表單)
阿新 • • 發佈:2018-11-07
import React, { Component } from 'react'; class ReactForm extends Component { constructor(props){ super(props) this.state={ msg:'表單', name:'111', sex:'1', city:'', citys:['北京','上海','深圳'], hobby:[ {'title':'睡覺','checked':true}, {'title':'吃飯','checked':false}, {'title':'打遊戲','checked':true} ], info:'' } } handelSubmit=(e)=>{ // 阻止submit的提交事件 e.preventDefault(); console.log(this.state.name) console.log(this.state.sex) console.log(this.state.city) console.log(this.state.hobby) console.log(this.state.info) } handelName=(e)=>{ this.setState({ name:e.target.value }) } handelSex=(e)=>{ this.setState({ sex:e.target.value }) } handelCity=(e)=>{ this.setState({ city:e.target.value }) } handelHobby=(key)=>{ var hobby=this.state.hobby; hobby[key].checked=!hobby[key].checked; this.setState({ hobby:hobby }) } handelInfo=(e)=>{ this.setState({ info:e.target.value }) } render() { return ( <div> <h2>{this.state.msg}</h2> <form onSubmit={this.handelSubmit}> 使用者名稱:<input type="text" value={this.state.name} onChange={this.handelName}/><br/> 男:<input type="radio" value='1' onChange={this.handelSex} checked={this.state.sex==1}/> 女:<input type="radio" value='2' onChange={this.handelSex} checked={this.state.sex==2}/><br/> 居住城市:<select value={this.state.city} onChange={this.handelCity}> { this.state.citys.map(function(value,key){ return <option key={key}>{value}</option> }) } </select><br/> 愛好:{// 注意this指向 this.state.hobby.map((vaule,key)=>{ return ( <span key={key}> {vaule.title}<input type="checkbox" checked={vaule.checked} onChange={this.handelHobby.bind(this,key)}/> </span>) }) }<br/> 備註: <textarea value={this.state.info} onChange={this.handelInfo}></textarea><br/><br/> <input type="submit" value='提交'/> </form> </div> ) } } export default ReactForm;
頁面長這樣(比較糙>_<)
填寫後點提交打印出來的結果