react 跨组件非父子数据通信 events eventBus事件通信
1、安装eventsyarnadd events --dev2、简单封装个eventBus的工具库/* utils/eventBus.js */import { EventEmitter } from 'events'export default new EventEmitter()3.例子应用Comp1 组件1import React from 'react';import Bus from '
·
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 点击后
更多推荐
已为社区贡献14条内容
所有评论(0)