Sử dụng event trong reactjs

Giới thiệu nội dung bài viết

Chào các em, hôm nay anh sẽ hướng dẫn mọi người hiểu về Event trong reactjs.

1. Sử dụng Event

Trong ví dụ đơn giản này chúng ta sẽ tạo sự kiện onClick. Khi người dùng click vào nút button ta sẽ gọi hàm updateState.

Chúng ta có file App.jsx như sau.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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;

reactjs

Chúng ta chạy chương trình trong file main.js như sau.

1
2
3
4
5
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

2. Sử dụng Event ở component con

Chúng ví dụ này chúng ta sẽ cập nhật giá trị state của component cha từ component con. Chúng ta tạo hàm để xử lý sự kiện updateState trong component cha, và truyền nó xuống component con thông qua thuộc tính prop updateStateProp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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;

Chúng ta chạy chương trình trong file main.js như sau.

1
2
3
4
5
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

reactjs

3. Video Demo


Mọi người hãy Subscribe kênh youtube dưới đây nhé để cập nhật các video mới nhất về kỹ thuật và kỹ năng mềm

Các khoá học lập trình MIỄN PHÍ tại đây


Comments