The event bus can be used in react; react uses the event bus to solve the event transfer between components. You can use a commonly used library events to complete the corresponding operations. It can be installed using npm or yarn. events, the syntax is "npm install events" and "yarn add events".
The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.
The event bus can be used in react
The problem solved by the react event bus: event transmission between components
If there is any problem in React development How to transfer events between components?
A. In Vue, we can quickly implement an event bus (EventBus) through an instance of Vue to complete the operation;
B. In React, we can rely on a commonly used library events to complete the corresponding operations;
How to implement
Use third-party library events to implement
common api
Create EventEmitter object: eventBus object
Emit an event: eventBus.emit("event name", parameter list)
Listen to events: eventBus.addListener("event name", Listening function)
Remove event: eventBus.removeListener("event name", listening function)
You need to install it before use. Choose one of the following two methods
npm install events yarn add events
events practice:
First create a new file QcEventEmitter.js. The content of the file is as follows:
import { EventEmitter } from 'events' class QcEventEmitter extends EventEmitter {}; export default new QcEventEmitter();
The following will implement the EventTest component to pass events to the Person component:
EventTest file content
A. Introduce QcEventEmitter into the EventTest component
B. Send events through QcEventEmitter.emit in the click event
import React, { Component } from 'react'; import QcEventEmitter from 'common/utils/QcEventEmitter' class EventTest extends Component { render() { return ( <div> <button onClick={e => this.btnCLick()}>测试event事件</button> </div> ); } btnCLick(){ QcEventEmitter.emit('contextClick', 'Lucy', '99') } }
export default EventTest;
Person file Content
A. QcEventEmitter is introduced in the Person component.
B. Listen for events through QcEventEmitter.addListener in componentDidMount.
C. Move through QcEventEmitter.removeListener in componentWillUnmount. In addition to monitoring events
import React, { Component, useContext } from 'react'; import QcEventEmitter from 'common/utils/QcEventEmitter' class Person extends Component { componentDidMount(){ QcEventEmitter.addListener("contextClick", this.headerClick) } componentWillUnmount() { QcEventEmitter.removeListener("contextClick", this.headerClick) } headerClick(name, age) { console.log(name, age); } render() { return ( <div> <h2 id="这是Person子组件">这是Person子组件</h2> </div> ); } } export default Person;
Render the EventTest component and the Person component in the App.js file (after the Person component is rendered, you can listen to the events emitted by EventTest, and there is no need for any dependencies between them)
import React from 'react'; import ContetTest from './pages/contenxt' import Person from 'pages/contenxt/person' function App() { return ( <div className="App"> <ContetTest /> <Person /> </div> ); } export default App;
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of Can event bus be used in react?. For more information, please follow other related articles on the PHP Chinese website!

TonavigateReact'scomplexecosystemeffectively,understandthetoolsandlibraries,recognizetheirstrengthsandweaknesses,andintegratethemtoenhancedevelopment.StartwithcoreReactconceptsanduseState,thengraduallyintroducemorecomplexsolutionslikeReduxorMobXasnee

Reactuseskeystoefficientlyidentifylistitemsbyprovidingastableidentitytoeachelement.1)KeysallowReacttotrackchangesinlistswithoutre-renderingtheentirelist.2)Chooseuniqueandstablekeys,avoidingarrayindices.3)Correctkeyusagesignificantlyimprovesperformanc

KeysinReactarecrucialforoptimizingtherenderingprocessandmanagingdynamiclistseffectively.Tospotandfixkey-relatedissues:1)Adduniquekeystolistitemstoavoidwarningsandperformanceissues,2)Useuniqueidentifiersfromdatainsteadofindicesforstablekeys,3)Ensureke

React's one-way data binding ensures that data flows from the parent component to the child component. 1) The data flows to a single, and the changes in the state of the parent component can be passed to the child component, but the child component cannot directly affect the state of the parent component. 2) This method improves the predictability of data flows and simplifies debugging and testing. 3) By using controlled components and context, user interaction and inter-component communication can be handled while maintaining a one-way data stream.

KeysinReactarecrucialforefficientDOMupdatesandreconciliation.1)Choosestable,unique,andmeaningfulkeys,likeitemIDs.2)Fornestedlists,useuniquekeysateachlevel.3)Avoidusingarrayindicesorgeneratingkeysdynamicallytopreventperformanceissues.

useState()iscrucialforoptimizingReactappperformanceduetoitsimpactonre-rendersandupdates.Tooptimize:1)UseuseCallbacktomemoizefunctionsandpreventunnecessaryre-renders.2)EmployuseMemoforcachingexpensivecomputations.3)Breakstateintosmallervariablesformor

Use Context and useState to share states because they simplify state management in large React applications. 1) Reduce propdrilling, 2) The code is clearer, 3) It is easier to manage global state. However, pay attention to performance overhead and debugging complexity. The rational use of Context and optimization technology can improve the efficiency and maintainability of the application.

Using incorrect keys can cause performance issues and unexpected behavior in React applications. 1) The key is a unique identifier of the list item, helping React update the virtual DOM efficiently. 2) Using the same or non-unique key will cause list items to be reordered and component states to be lost. 3) Using stable and unique identifiers as keys can optimize performance and avoid full re-rendering. 4) Use tools such as ESLint to verify the correctness of the key. Proper use of keys ensures efficient and reliable React applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor
