ReactJS - 表格

在本章中,我们将学习如何在React中使用表单.

简单示例

在以下示例中,我们将设置一个 value = {this.state.data} 的输入表单.这允许在输入值改变时更新状态.我们正在使用 onChange 事件来监视输入更改并相应地更新状态.

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'));

当输入文本值发生变化时,状态将会更新.

React Forms Simple

复杂示例

在以下示例中,我们将看到如何使用子组件的表单. onChange 方法将触发状态更新,该状态更新将传递给子输入并在屏幕上呈现. "事件"一章中使用了类似的示例.每当我们需要从子组件更新状态时,我们需要传递将处理更新的函数( updateState )作为prop( updateStateProp ).

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'));

这将产生以下结果.

React Forms Complex