第3期 Context

118 阅读1分钟
const MyContext = React.createContext({test:1});
const {Provider,Consumer} = MyContext;

import Child from './Child';
Child.contextType = MyContext;
{this.context.test}

Context的作用

可以跨组件使用变量

相关语法

1、此处有Provider,不使用默认值{test:1}。

const MyContext = React.createContext({test:1});
const {Provider,Consumer} = MyContext;

<Provider value={{test:2}}>
    <Consumer>
        {(value)=>{
            return <div>{value.test}</div> // 2
        }}
    </Consumer>
</Provider>

2、此处没有Provider,使用默认值{test:1}。

const MyContext = React.createContext({test:1});
const {Provider,Consumer} = MyContext;
<Consumer>
    {(value)=>{
        return <div>{value.test}</div> // 1
    }}
</Consumer>

3、contextType

const MyContext = React.createContext({test:1});
const {Provider,Consumer} = MyContext;
import Child from './Child';
Child.contextType = MyContext;

// 设置Child.contextType = MyContext之后,可以再Chil中通过{this.context.test}获取到test的值。