Câu hỏi phỏng vấn Reactjs
Câu hỏi

How to bind methods or event handlers in JSX callbacks?

Câu trả lời

In React, binding methods or event handlers in JSX callbacks is crucial for ensuring that the this keyword within the methods refers to the component instance. There are several ways to handle this binding, each with its own use cases and implications for performance and readability. Here are the primary methods:

1. Binding in the Constructor

This is a traditional and widely recommended approach for binding event handlers in React components, especially when considering performance. By binding methods in the constructor, you ensure that the function is bound just once during the lifecycle of the component, thus avoiding unnecessary function re-creation on each render.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log('Button clicked');
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

2. Class Properties as Arrow Functions

Using arrow functions as class properties is an increasingly popular syntax that ensures this is automatically bound to the component. This approach is cleaner and avoids the need to explicitly bind this in the constructor.

class MyComponent extends React.Component {
  handleClick = () => {
    console.log('Button clicked');
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

3. Arrow Functions in Render

You can use arrow functions directly in the JSX callback. This method is straightforward and easy to implement but can lead to performance issues if not used carefully, as it creates a new function on each render.

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

How would you store non-state/instance variables in functional React components?

junior

What is state in React?

senior

Explain why and when would you use useMemo() ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào