在一个典型的 React 应用中,数据是通过 props 属性自上而下(由父及子)进行传递的,但这种做法对于某些类型的属性而言是极其繁琐的(例如:地区偏好,UI 主题),这些属性是应用程序中许多组件都需要的。Context 提供了一种在组件之间共享此类值的方式,而不必显式地通过组件树的逐层传递 props。

    基本用法
    1.使用React.createContext创建Context,可传入一个默认值:

    1. const MyContext = React.createContext({count: 0})

    2.上层组件中使用Context.Provider提供value

    1. function App() {
    2. const [count, setCount] = useState(0);
    3. return (
    4. <MyContext.Provider value={{ count }}>
    5. <button onClick={() => setCount(count + 1)}>+</button>
    6. <Child1 />
    7. <Child2 />
    8. <Child3 />
    9. </MyContext.Provider>
    10. );
    11. }

    3.子组件中使用Context:

    • 类组件 ```javascript // 方式1 class Child1 extends Component { static contextType = MyContext;

      render() { return

      {this.context.count}
      } }

    // 方式2 class Child2 extends Component { render() { return {context =>

    {context.count}
    } ; } }

    1. - hooks
    2. ```javascript
    3. export const Child3 = () => {
    4. const context = useContext(MyContext);
    5. return <div>{context.count}</div>
    6. }