react跨组件通信
2021/4/22 18:55:11
本文主要是介绍react跨组件通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
在react没有类似vue中的事件总线来解决这个问题,一是我们借助它们共同的父级组件通过代理的方式来实现,但过程会相当繁锁。react提供了Context来实现跨组件通信, 而不必显式地通过组件树的逐层传递 props。
import React, { Component, createContext } from 'react'
const {
Provider,
Consumer
} = createContext()
祖先与子孙之间的通信
组件节点
import React, { Component } from 'react'import MyContext from '../context/Bus'
import Cmp2 from './Cmp2' export default class Cmp1 extends Component { static contextType = MyContext state = { userinfo: { username: '张三', age: 20 } } render() { return ( <div> {/* 发布一个消息 父子向下N多层的传递 祖先与后代的关系 */} <MyContext.Provider value={this.state.userinfo}> <Cmp2 /> </MyContext.Provider> </div> ) } }
子孙节点
import React, { Component } from 'react' import MyContext from '../context/Bus' export default class Cmp2 extends Component { // 统一数据源中的 context中的参数据数据 // static contextType = MyContext render() { // console.log(this.context) return ( <div> {/* {this.context} */} {/* 消费一下 */} <MyContext.Consumer> { // 函数 参数就是你订阅的数据 value => ( <div> 您的姓名为:{value.username} </div> ) } </MyContext.Consumer> </div> ) } }
Bus.js文件
import React, { createContext } from 'react' const db = { user1: { username: '张三' }, user2: { username: '李四' } } // 如果createContext中有参数值,则表示 Provider中的没有写value值 //相当于value的默认值 // 使用默认值,可以实现平级 // Bus强一点,强在有数据 比vuex弱很多,只能获取 // export const MyContext = createContext(db.user1) const MyContext = createContext(db.user1) export { db, MyContext as default }
这篇关于react跨组件通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28基于Python+Vue开发的口腔牙科预约管理系统
- 2024-09-28基于Python+Vue开发的酒店客房预订管理系统
- 2024-09-27使用js将ETH账户的资产打散其他账户web3
- 2024-09-27我轻松地将我的 React.js 应用程序翻译成了多种语言。下面是我是如何做到的... ??
- 2024-09-27?? 使用 useMemo 和 useCallback 加速 React:告别缓慢的重新渲染!??
- 2024-09-27Vue CLI多环境配置教程:新手入门指南
- 2024-09-27Vue CLI多环境配置教程:快速入门指南
- 2024-09-27Vue CLI教程:新手入门指南
- 2024-09-27Vue CLI教程:初学者快速入门指南
- 2024-09-27Vue3公共组件教程:入门与实践