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

Describe how events ...

Câu trả lời

In React, events are handled using a synthetic event system, which provides a cross-browser interface to native events. This system wraps the native event in order to ensure that they have consistent properties across different browsers. Here's a detailed explanation of how events are handled in React:

Synthetic Events

React creates a SyntheticEvent wrapper around the browser's native event. This wrapper normalizes events to make sure they have the same properties across different browsers. The synthetic event has the same interface as the native event, including methods like stopPropagation() and preventDefault(), except that these methods work identically across all browsers[11].

Event Handlers

Event handlers in React are passed as props to components and are written using camelCase naming conventions. For example, the onClick event in HTML is written as onClick in JSX[9]. When an event occurs, the specified handler is executed. Event handlers in React can be written as methods of a class component or functions in functional components.

Binding Event Handlers

In class components, it is necessary to bind event handlers to the instance of the component to ensure that the this keyword within the handler refers to the component. This can be done in the constructor or by using class field syntax to automatically bind methods[9][12].

Passing Arguments

Event handlers can also receive additional arguments besides the event object. This is commonly done by using an arrow function that calls the handler function with the event object and any additional arguments[9].

Event Pooling

React employs event pooling to improve performance. The SyntheticEvent object is pooled, meaning that it is reused for different events. Because of this, properties of the event object may be nullified by the time they are used in an asynchronous code. To work around this, you can use the event.persist() method, which removes the event from the pool and allows the event to be retained in user code[11].

Functional Components and Hooks

With the introduction of hooks in React 16.8, functional co...

senior

senior

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

junior

What is the difference between Component and Container in Redux?

senior

What is difference between Incremental DOM and Virtual DOM?

middle

What would be the common mistake of function being called every time the component renders?

Bình luận

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

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