事件总线

2022-05-12  本文已影响0人  张_何
import React, { PureComponent } from 'react';
import { EventEmitter } from 'events';

// 事件总线: event bus
const eventBus = new EventEmitter();

class Home extends PureComponent {
  // 一般在这里监听,因为监听只需要一次
  componentDidMount() {
    eventBus.addListener("sayHello", this.handleSayHelloListener);
  }
  // 有监听就要有移除监听
  componentWillUnmount() {
    eventBus.removeListener("sayHello", this.handleSayHelloListener);
  }

  handleSayHelloListener(num, message) {
    console.log(num, message);
  }

  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", 123, "Hello Home");
  }
}

export default class App extends PureComponent {
  render() {
    return (
      <div>
        <Home/>
        <Profile/>
      </div>
    )
  }
}
上一篇下一篇

猜你喜欢

热点阅读