Events

Trong chương này, chúng ta sẽ học cách sử dụng các sự kiện.

Ví dụ đơn giản

Đây là một ví dụ đơn giản mà chúng tôi sẽ chỉ sử dụng một component. Chúng tôi chỉ thêm sự kiện onClick sẽ kích hoạt chức năng updateState khi nút được nhấ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() {

      this.setState({data: 'Data updated...'})

   }

   render() {

      return (

         <div>

            <button onClick = {this.updateState}>CLICK</button>

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

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

 

Child Events

Khi chúng ta cần cập nhật trạng thái của component cha từ con của nó, chúng ta có thể tạo một trình xử lý sự kiện ( updateState ) trong component cha và chuyển nó dưới dạng một phần mềm hỗ trợ ( updateStateProp ) cho component con mà chúng ta có thể gọi nó.

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() {

      this.setState({data: 'Data updated from the child component...'})

   }

   render() {

      return (

         <div>

            <Content myDataProp = {this.state.data}

               updateStateProp = {this.updateState}></Content>

         </div>

      );

   }

}

class Content extends React.Component {

   render() {

      return (

         <div>

            <button onClick = {this.props.updateStateProp}>CLICK</button>

            <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.