import React,{ Component } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import * as serviceWorker from './serviceWorker'; class MyInput extends Component{ constructor(props){ super(props); this.state={ text:'请输入内容' } this.textFn=this.textFn.bind(this); } textFn(e){ .setState({ text:e.target.value }) } render(){ return( <div> <input type="text" onChange={this.textFn} placeholder={this.state.text}/> <p>{this.state.text}</p> </div> ) } } ReactDOM.render( <div> <MyInput /> </div>,document.getElementById('example') ); serviceWorker.unregister();
如何在子组件上使用表单
在父组件通过创建事件句柄 (handleChange) ,并作为 prop (updateStateProp) 传递到子组件上
import React,1)">; class Parent extends Component{ constructor(props){ super(props); ( <Child textFn={this.textFn} text={this.state.text} /> ) } } class Child extends Component{ render(){ this.props.textFn} placeholder={this.props.text}/> <p>{this.props.text}</p> </div> ) } } ReactDOM.render( <div> <Parent /> </div>,1)">) ); serviceWorker.unregister();
在 React 中,不使用 selected 属性,而在根 select 标签上用 value 属性来表示选中项
import React,1)">; class Select extends Component{ constructor(props){ super(props); { text:''this.selectFn=this.selectFn.bind(); this.submitFn=this.submitFn.bind(); } selectFn(e){ .setState({ text:e.target.value }) } submitFn(e){ console.log('you choosed '+.state.text); e.preventDefault(); } render(){ ( <form onSubmit={this.submitFn}> <select value={this.state.text} onChange={this.selectFn}> <option value="a">a</option> <option value="b">b</option> <option value="c">c</option> </select> <input type="submit" value="提交" /> </form> ) } } ReactDOM.render( <div> <Select /> </div>,1)">) ); serviceWorker.unregister();
处理多个 input 元素时,可以给每个元素添加一个 name 属性,来让处理函数根据 event.target.name 的值来选择做什么
import React,1)">{ text:true,num:4this.changeFn=this.changeFn.bind(); } changeFn(e){ const value=e.target.type==='checkBox' ? e.target.checked : e.target.value; const name=e.target.name; .setState({ [name]:value }) } render(){ ( <form> <input type="checkBox" name="text" checked={this.changeFn} /> <br/> <input type="number" name="num" value={this.state.num} onChange={this.changeFn} /> </form> ) ); serviceWorker.unregister();