react实现上下文context

context.js文件

import React from "react";
export const resume = {
  base: {
    name: "",
    age: "",
    genders: "male",
  }
};

export const context = React.createContext(resume.base);

index.jsx(最大的父组件)

import React, { Component } from "react";
import Child from "./Children";//直系子组件
import { context, resume } from "./context";//context.js
import About from "./about";//一个组件
class index extends Component {
  constructor() {
    super();
    this.state = {
      base: { name: "", age: "", genders: "male" },
    };
  }
  _init() {
    this.setState({
      base: {
        name: "新名字",
        age: "32",
        genders: "nv",
      },
    });
  }
  componentDidMount() {
    setTimeout(() => {
      this._init();
    }, 2000);
  }
  contextFn(txt) {
    console.log(txt);
  }
  left() {
    return <div>left</div>;
  }
  com() {
    return <About />;
  }
  render() {
    console.log(resume);
    return (
      <>
        <context.Provider
          value={{
            base: this.state.base, //基础数据类型
            callback: this.contextFn, //子组件回调 信息返回
            left: this.left, //直接接收某些内容
            com: this.com, //可以直接接收某个组件
          }}
        >
          <Child />
        </context.Provider>
      </>
    );
  }
}

export default index;

直系子级Children.jsx

import React, { Component } from "react";
import Child2 from "./Children2";
class Children extends Component {
  render() {
    return (
      <div>
        <b>大子级</b>
        <Child2 />
      </div>
    );
  }
}

export default Children;

非直系子级Children2.jsx

import React, { Component } from "react";
import { context } from "./context";//context.js
class Children extends Component {
  list(txt) {
    console.log(txt);
  }
  // 第二种
  // static contextType = context;

  // 第一种
  componentDidMount() {
    const { genders } = this.context;
  }
  render() {
    const { genders } = this.context;
    // console.log(this.context);
    return (
      <>
        {genders}++
        <context.Consumer>
          {(value) => {
            return (
              <b>
                {this.list(value.base)}
                {value.base.genders}
                {value.left()}
                {value.com()}
                {value.callback("fn")}
              </b>
            );
          }}
        </context.Consumer>
      </>
    );
  }
}

// 第三种
// Children.contextType = context;
export default Children;

About.jsx组件(就是需要传递的一个组件)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值