Forms

Trong chương này, chúng ta sẽ học cách sử dụng các biểu mẫu trong React.

Ví dụ đơn giản

Trong ví dụ sau, chúng tôi sẽ đặt một biểu mẫu đầu vào với giá trị = {this.state.data} . Điều này cho phép cập nhật trạng thái bất cứ khi nào giá trị đầu vào thay đổi. Chúng tôi đang sử dụng sự kiện onChange sẽ xem các thay đổi đầu vào và cập nhật trạng thái cho phù hợp.

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

Khi giá trị văn bản đầu vào thay đổi, trạng thái sẽ được cập nhật.

 

Ví dụ phức tạp

Trong ví dụ sau, chúng ta sẽ thấy cách sử dụng các biểu mẫu từ component con. Phương thức onChange sẽ kích hoạt cập nhật trạng thái sẽ được chuyển đến giá trị đầu vào con và hiển thị trên màn hình. Một ví dụ tương tự được sử dụng trong chương Sự kiện. Bất cứ khi nào chúng ta cần cập nhật trạng thái từ thành phần con, chúng ta cần chuyển hàm sẽ xử lý việc cập nhật ( updateState ) như một phần mềm hỗ trợ ( 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'));

Điều này sẽ tạo ra kết quả sau.