React教程12:Form表单处理
这一篇教程,我们将教你如何在React中使用Form。
一个简单的React Form例子
这个例子中我们设置了input的 value = {this.state.data}. 当input的value变化后,就会即时更新state。
我们使用onChange 事件来监视input的变化和state的更新。
App.jsx
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 'Initial data...' } this.updateState = this.updateState.bind(this); }; updateState(e) { this.setState({data: e.target.value}); } render() { return ( <div> <input type = "text" value = {this.state.data} onChange = {this.updateState} /> <h4>{this.state.data}</h4> </div> ); } } export default App;
main.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app'));
当input的value变化后,state也会更新。![]()
一个较复杂的React Form例子
这个例子演示的是如何对child component中的form进行操作。 onChange 方法会触发来自child input value 引发的state更新,并render在屏幕上。当你需要更新child component中的state时,你需要使用处理把(updateState) 当做prop (updateStateProp) 的function。
App.jsx
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 'Initial data...' } this.updateState = this.updateState.bind(this); }; updateState(e) { this.setState({data: e.target.value}); } render() { return ( <div> <Content myDataProp = {this.state.data} updateStateProp = {this.updateState}></Content> </div> ); } } class Content extends React.Component { render() { return ( <div> <input type = "text" value = {this.props.myDataProp} onChange = {this.props.updateStateProp} /> <h3>{this.props.myDataProp}</h3> </div> ); } } export default App;
main.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app'));
显示下面的效果: