1、插件简介
- 工具库:PubSubJS
- 下载:
yarn add pubsub-js
- 使用:
- 引入:
import PubSub from 'pubsub-js'
- 订阅:
var messageId = PubSub.subscribe('delete', function(data){ })
- 取消订阅:
PubSub.unsubscribe(messageId )
- 发布:
PubSub.publish('delete', data)
- 引入:
2、Demo
2.1、项目结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Jvs4jj2e-1669626462065)(C:\Users\Administrator\Desktop\学习笔记\react_脚手架.assets\image-20221128163745052.png)]
2.2、CODE
2.2.1、App.js
import React, { Component } from 'react'
import A from './components/A'
import B from './components/B'
export default class App extends Component {
render() {
return (
<div>
<A />
<B />
</div>
);
}
}
2.2.2、A.jsx
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class A extends Component {
render() {
return (
<div>
<button onClick={() => PubSub.publish('A_Pub', '这是A发布的一条消息')}>A发布消息</button>
</div>
)
}
}
2.2.3、B.jsx
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class B extends Component {
state = {
message: ''
}
componentDidMount() {
PubSub.subscribe('A_Pub', (_, message) => this.setState({ message }))
}
render() {
return (
<div>B接收的消息:{this.state.message}</div>
)
}
}