React 组件通讯 (pubsub-js 发布订阅 依赖)

在 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 详情

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值