1、安装events

 yarn  add events --dev

2、简单封装个eventBus的工具库

/* utils/eventBus.js */

import { EventEmitter } from 'events'
export default new EventEmitter()

3.例子应用

  • Comp1 组件1

import React from 'react';
import Bus from 'utils/eventBus'

export default function Comp1 (props) {

  const data = {
    msg: 'msg comes from comp1'
  }

  const handleClick = () => {
    console.log('click comp1')
    Bus.emit('is_from_comp1', data)
  }

  return (
    <h2 className="Comp1">
      组件1
      <button onClick={handleClick}>点击</button>
    </h2>
  )
}

  • Comp2 组件2
import React, { useEffect, useState } from 'react';
import Bus from 'utils/eventBus'

export default function Comp2 (props) {
  const [msg, setMsg] = useState('comp2 default msg')

  useEffect(() => {
    Bus.addListener('is_from_comp1', data => {
      console.log(2, data);
      setMsg(data.msg)
    })
  }, [])

  return (
    <h2 className="Comp2">
      组件2  <span>{msg}</span>
    </h2>
  )
}

效果:

1
在这里插入图片描述
2 点击后
在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐