Article directory
foreword
Today, I will introduce another way of passing values in react - using evenbus to pass values, it is still the same as a small case to explain its specific usage
Brother component pass value
In the sibling components, the eventbus event bus is used for communication, and the publish-subscribe event bus is used for communication. To use evenbus we first need to download it
Download events:
yarn add -D events
Then create a new event.js file as follows:
import {
EventEmitter } from "events"
// 导入事件总线,利用这个对象发射和监听事件,这个对象是全局的
const eventBus = new EventEmitter()
export default eventBus
We come to brother component A, introduce eventBus, and then use emit to send events:
pay attention to the format of sending: send event eventBus.emit('event name', parameter 1, parameter 2)
import React, {
Component } from 'react'
import eventBus from './event'
export class Header extends Component {
send = () => {
let name = '点赞关注,好好学前端'
let arr = [1, 2, 3, 4]
// 发送事件eventBus.emit('事件名', 参数1, 参数2)
eventBus.emit('sayHello', name, arr)
}
render() {
return (
<div>Header Page
<button onClick={
this.send}>发送事件给footer组件</button>
</div>
)
}
}
export default Header
Brother component B receives data and prints it when processing the listening event:
import React, {
Component } from 'react'
import eventBus from './event'
export class Footer extends Component {
// 添加事件监听,监听从header组件发送过来的sayHello事件
componentDidMount() {
eventBus.addListener('sayHello', this.sayHelloContent)
}
// 处理监听事件
sayHelloContent(a, b) {
console.log(a, b)
}
// 移除事件监听
componentWillUnmount() {
eventBus.removeListener('sayHello', this.sayHelloContent)
}
render() {
return (
<div>Footer</div>
)
}
}
export default Footer
Click the button to trigger the click event of the A component, and take a look at the result:
This completes the value transfer between sibling components. Let's summarize the usage:
Evenbus usage summary
- Download events:
yarn add -D events
- Create a new event.js file and write the following content:
import {
EventEmitter } from "events"
// 导入事件总线,利用这个对象发射和监听事件,这个对象是全局的
const eventBus = new EventEmitter()
export default eventBus
- Introduce eventBus to the page that needs to send events, and then use emit to send events
// 发送事件eventBus.emit('事件名', 参数)
eventBus.emit('sayHello', name, arr)
- Introduce eventBus to the page that needs to receive events, and then use addListener to listen for events
// 添加事件监听,监听从header组件发送过来的sayHello事件
componentDidMount() {
eventBus.addListener('sayHello', this.sayHelloListener)
}
// 处理事件监听
sayHelloListener(a, b){
console.log(a, b) // 这样就拿到从另一个兄弟组件中传过来的值了
}
- Remove event listeners, in the life cycle componentWillUnmount
// 移除事件监听
componentWillUnmount() {
eventBus.removeListener('sayHello', this.sayHelloListener)
}
Well, this article is over. If it is helpful to you, please like, follow and support it~ I
will bring you more high-quality content in the future~