Reactjs - Events

04/01/2022   React

Reactjs - Events

Reactjs - Events

Cũng giống như HTML, React có thể thực hiện các hành động dựa trên các sự kiện của người dùng.

React có các sự kiện tương tự như HTML: nhấp chuột, thay đổi, di chuột qua, v.v

1. Thêm sự kiện
Các sự kiện React được viết theo cú pháp camelCase:
onClick thay vì onclick.
Các trình xử lý sự kiện React được viết bên trong dấu ngoặc nhọn:
onClick = {shoot} thay vì onClick = "shoot ()".

import React from 'react';
import ReactDOM from 'react-dom';
function shoot() {
  alert("Great Shot!");
}
const myelement = (
  <button onClick={shoot}>Take the shot!</button>
);

ReactDOM.render(myelement, document.getElementById('root'));

2. Quản lý sự kiện
Một thực tiễn tốt là đặt trình xử lý sự kiện như một phương thức trong lớp component:

Put the shoot function inside the Football component:

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
  shoot() {
    alert("Great Shot!");
  }
  render() {
    return (
      <button onClick={this.shoot}>Take the shot!</button>
    );
  }
}

ReactDOM.render(<Football />, document.getElementById('root'));

3. Từ khóa this
Đối với các phương thức trong React, từ khóa this phải đại diện cho component sở hữu phương thức.

Đó là lý do tại sao bạn nên sử dụng các hàm mũi tên. Với các hàm mũi tên, điều này sẽ luôn đại diện cho đối tượng đã xác định hàm mũi tên.

class Football extends React.Component {
  shoot = () => {
    alert(this);//this ở đây là đối tượng component
    /*
    arrow function lấy scope từ the parent đó chính là window object.
    The 'this' keyword refers to the component object
    */
  }
  render() {
    return (
      <button onClick={this.shoot}>Take the shot!</button>
    );
  }
}

ReactDOM.render(<Football />, document.getElementById('root'));

Ví dụ không xác định được this vì không tạo đối tượng

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
  shoot() {
    alert(this); // không biết this là gì, không xác định được vì chưa tạo đối tượng
  }
  render() {
    return (
      <button onClick={this.shoot}>Take the shot!</button>
    );
  }
}

ReactDOM.render(<Football />, document.getElementById('root'));

Tại sao lại sử dụng hàm mũi tên?
Trong các component lớp, từ khóa this không được xác định theo mặc định, vì vậy với các hàm thông thường, từ khóa this đại diện cho đối tượng được gọi là phương thức, có thể là đối tượng cửa sổ chung, nút HTML hoặc bất cứ thứ gì.

Nếu bạn phải sử dụng các hàm thông thường thay vì các hàm mũi tên, bạn phải liên kết nó với cá thể component bằng phương thức bind ():

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
  constructor(props) {
    super(props)
    this.shoot = this.shoot.bind(this)
  }
  shoot() {
    alert(this);
    /*
    Thanks to the binding in the constructor function,
    the 'this' keyword now refers to the component object
    */
  }
  render() {
    return (
      <button onClick={this.shoot}>Take the shot!</button>
    );
  }
}

ReactDOM.render(<Football />, document.getElementById('root'));

4. Truyền đối số
Nếu bạn muốn gửi các tham số vào một trình xử lý sự kiện, bạn có hai tùy chọn:

* Tạo một hàm mũi tên ẩn danh Hoặc là: Ràng buộc trình xử lý sự kiện với this.

a. Make an anonymous arrow function:

VD1: Send "Goal" as a parameter to the shoot function, using arrow function:

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
  shoot = (a) => {
    alert(a);
  }
  render() {
    return (
      <button onClick={() => this.shoot("Goal")}>Take the shot!</button>
    );
  }
}

ReactDOM.render(<Football />, document.getElementById('root'));

hoặc

b. Bind the event handler to this.
Note that the first argument has to be this.

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
  shoot(a) {
    alert(a);
  }
  render() {
    return (
      <button
        onClick={this.shoot.bind(this, "Goal")}
      >Take the shot!</button>
    );
  }
}

ReactDOM.render(<Football />, document.getElementById('root'))

Lưu ý về ví dụ thứ hai: Nếu bạn gửi các đối số mà không sử dụng phương thức liên kết (bind), (this.shoot (this, "Goal") thay vì this.shoot.bind (this, "Goal")), hàm shoot sẽ được thực thi khi trang được tải thay vì chờ nhấp vào button.

  • .bind(): gắn hàm xử lý đó với component instance trong constructor thông qua hàm .bind()
  • Arrow function: Sử dụng Arrow function là một giải pháp vì nó dùng lexical this binding nên sẽ tự động gắn hàm đó vào scope mà nó được định nghĩa.

5. Đối tượng Event React
Bộ xử lý sự kiện có quyền truy cập vào sự kiện React đã kích hoạt chức năng.
Trong ví dụ của chúng tôi, sự kiện là sự kiện "nhấp chuột". Lưu ý rằng một lần nữa cú pháp có khác khi sử dụng các hàm mũi tên hay không.
Với hàm mũi tên, bạn phải gửi đối số sự kiện theo cách thủ công:

Arrow Function: Gửi đối tượng sự kiện theo cách thủ công:

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
  shoot = (a, b) => {
    alert(b.type);
    /*
    'b' represents the React event that triggered the function,
    in this case the 'click' event
    */
  }
  render() {
    return (
      <button
        onClick={(ev) => this.shoot("Goal", ev)}
      >Take the shot!</button>
    );
  }
}

ReactDOM.render(<Football />, document.getElementById('root'));

Không có hàm mũi tên, đối tượng event React được gửi tự động làm đối số cuối cùng khi sử dụng phương thức bind ():

With the bind() method, the event object is sent as the last argument:

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
  shoot = (a, b) => {
    alert(b.type);
    /*
    'b' represents the React event that triggered the function,
    in this case the 'click' event
    */
  }
  render() {
    return (
      <button
        onClick={this.shoot.bind(this, "Goal")}
      >Take the shot!</button>
    );
  }
}

ReactDOM.render(<Football />, document.getElementById('root'));

 

Cám ơn.

Bài viết cùng chủ đề