赞助

写入组件

import React, { Component } from 'react'
//下面二个就是兄弟关系的组件
import Cmp1 from '../Child/Cmp1' import Cmp2 from '../Child/Cmp2' import MyContext, { db } from '../context/Bus' export default class Sub extends Component { constructor(props) { super(props); this.state = { user: db.user2 } } render() { return ( <MyContext.Provider value={this.state.user}> <Cmp1 /> <Cmp2 /> <button onClick={this.fn.bind(this)}>按钮一下</button> </MyContext.Provider> ) } fn() { this.setState({ user: db.user1 }) } }

Cmp2文件

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} 
      </div>
    )
  }
}

Bus.js文件

import React, { createContext } from 'react'

// 如果createContext中有参数值,则表示 Provider中的没有写value值
//相当于value的默认值
// 使用默认值,可以实现平级
//  Bus强一点,强在有数据  比vuex弱很多,只能获取
// export const MyContext = createContext(db.user1)

export const MyContext = createContext('共同的数据')

 

posted on 2021-04-22 18:00  Tsunami黄嵩粟  阅读(78)  评论(0编辑  收藏  举报