事件总线 event bus
作者:互联网
import React, { PureComponent } from 'react' import {EventEmitter} from 'events'; // yarn add events
// 事件总线 event bus const eventBus = new EventEmitter();
class Home extends PureComponent{
componentDidMount(){ eventBus.addListener('sayHello',this.handleSayHelloListener) }
componentWillUnmount(){ eventBus.removeListener('sayHello',this.handleSayHelloListener); }
handleSayHelloListener(...args){ console.log(args); }
render() { return ( <div> Home </div> ) } }
class Profile extends PureComponent{ render() { return ( <div> Profile <button onClick={e =>this.emmitEvent()}>点击的Profile按钮</button> </div> ) }
emmitEvent(){ // eventBus.emit("sayHello","hello home",'123') // eventBus.emit("sayHello","hello home",'123',{ // id:1, // age:25 // })
eventBus.emit("sayHello",{ id:1, age:25 }) } }
export default class App extends PureComponent { render() { return ( <div> <Home /> <Profile /> </div> ) } }
标签:Profile,render,bus,handleSayHelloListener,总线,event,sayHello,PureComponent,eventB 来源: https://www.cnblogs.com/eric-share/p/15132046.html