在 react 中传统的组件通讯写法繁琐,对于兄弟组件传值需要外层父组件接过来再传过去
通过使用第三方依赖:pubsub-js
yarn add pubsub-js
npm install pubsub-js
通过,订阅 ----> 发布 的模式实现组件之间的通讯,以及任意组件通讯。
react 组件A
import React, { Component } from 'react'
import PubSub from 'pubsub-js' // 引入 pubsub-js 第三方依赖
export default class CompA extends Component {
state = { txt: null }
// 一般我们在组件挂在的时候绑定订阅
componentDidMount() {
/*
PubSub.subscribe 订阅
第一个参数是 订阅名 ,发布的时候通过指定订阅名传递数据
第二个参数是 callBack ,该方法有两个参数第一个是当前订阅名,第二个是接过来的参数
由于我们一般用不到第一个参数 一般这么写 ----> (_,data) => {}
*/
// 这儿通过 token 指定当前 PubSub.subscribe 方法返回的订阅器Topic
this.token = PubSub.subscribe('Topic', (_, data) => {
console.log('_ ---> ', _)
console.log('data ---> ', data)
this.setState({ txt: data.a }) // 更改新的数据状态
})
// add the function to the list of subscribers to a particular topic
// we're keeping the returned token, in order to be able to unsubscribe
// from the topic later on
}
// 一般在组件将要卸载 写清除订阅
componentWillUnmount() {
// PubSub.unsubscribe 清楚指定订阅器
PubSub.unsubscribe(this.token);
}
render() {
return (
<div className='comp-a'>
<h1>CompA</h1>
<h2>接受过来的数据为:{this.state.txt}</h2>
</div>
)
}
}
react 组件B
import React, { Component } from 'react'
import PubSub from 'pubsub-js' // 引入 pubsub-js 第三方依赖
export default class CompB extends Component {
handleSent = () => {
// 通过方法触发 发布 publish 方法
/*
PubSub.publish 发布
第一个参数是 指定的 订阅名
第二个参数是 要传递的数据
*/
PubSub.publish('Topic', { a: 'Hello' })
}
render() {
return (
<div className='comp-b'>
<h1>CompB</h1>
<button onClick={this.handleSent}>发送数据</button>
</div>
)
}
}
效果
pubsub-js 详情