直接来看吧!!

一般组件之间传参通过props,今天记录一下Context

使用场景:组件嵌套层级很深的情况

在我们很多的场景中我们都喜欢封装js实现多地方引用!所以写一个单独的Context一便以后使用 GlobalContext.js

import React from 'react'
 
const GlobalContext = React.createContext()

export default GlobalContext

Father.jsx

import GlobalContext from './GlobalContext' //引入上面定义的context
import Son from './Son ' // 引入子组件
class Home extends React.Component {
    state = {
        name:'屈小康'
    }
    render() {
        
        return (
            <div>
           <GlobalContext.Provider value={{name:this.state.name}}>
            <Son ></Son >
           </GlobalContext.Provider>
            </div>
        )
    }

}
export default Home

Son.jsx

import React from 'react'
import GlobalContext from '../GlobalContext';//引入上面定义的context
class Son extends React.Component {

    static contextType = GlobalContext;

    render() {
     
        console.log(this.context);
      
        return (
         <span>{this.context.name}</span>
        )

    }

}

export default Son

这就是最简单的用法了!