新版 react context的写法

祖组件:

import React, { createContext, Context } from "react";
import CNode from "../components/CNode";

type propsType = {};
type stateType = {
  userInfo: any,
};
//这里要导出这个上下文,下面的子孙组件哪个用到context的东西哪个就引入一下
export const InfoContext: Context<any> = createContext({
  name: "",
  age: 0,
});
class Test extends React.Component<propsType, stateType> {
  constructor(props) {
    super(props);
    this.state = {
      userInfo: {
        name: "test",
        age: -1,
      },
    };
  }
  handleClick = () => {
    let info = {
      name: "ls",
      age: 20,
    };
    this.setState({
      userInfo: info,
    });
  };
  render() {
    return (
      <InfoContext.Provider value={this.state.userInfo}>
        <button onClick={() => this.handleClick()}>传递</button>
        <CNode></CNode>
      </InfoContext.Provider>
    );
  }
}
export default Test;

子组件:

import React from "react";
import SNode from "../components/SNode";
type propsType = {};
type stateType = {};

class Test extends React.Component<propsType, stateType> {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <div>
        中间的子组件
        <SNode></SNode>
      </div>
    );
  }
}
export default Test;

孙组件:

import React from "react";
import {InfoContext} from '../components/GPNode'//引入上下文
type propsType = {};
type stateType = {};

class Test extends React.Component<propsType, stateType> {
constructor(props) {
super(props);
this.state = {};
//不写在这里的话初始化的时候不会获取到传递的context
Test.contextType = InfoContext;
}
render() {
return (
<div>
最下面的孙子组件
<br/>
<label>姓名:{this.context.name}</label>
<br/>
<label>年龄:{this.context.age}</label>
</div>
);
}

}

export default Test;

也可以用孙组件以消费者的插件模式这么写:

import React from "react";
import { InfoContext } from "./GPNode"; //引入上下文

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    //不写在这里的话初始化的时候不会获取到传递的context
    Test.contextType = InfoContext;
    console.log(InfoContext);
  }
  render() {
    return (
      <div>
        <label>最下面的孙子组件jsx</label>
        <br />
        <InfoContext.Consumer>
          {(val) => (
            <div>
              <label>姓名:</label> <div>{val.name}</div>
              <label>年龄</label> <div>{val.age}</div>
            </div>
          )}
        </InfoContext.Consumer>
      </div>
    );
  }
}
Test.displayName = "ssss";
export default Test;


但是这里有个问题就是没有探测出context的默认值是在哪个地方可以触发,根据官方的文档来看了半天摸不着头脑,有知道的大神麻烦赐教

posted @ 2020-06-03 10:33  洛晨随风  阅读(543)  评论(0编辑  收藏  举报