1. 定义:useContext是react的一个Hook,它允许你跨层级访问context的值,而不用一层一层的手动传props;
2. 使用场景:设置一些全局状态,比如主题色,用户认证信息等,可以在根组件设置,在所需要用到的地方去获取值;
3. 使用步骤:
3.1 在顶层组件中创建context对象
import React from 'react';
const contextValue = React.createContext(initValue);
3.2 在顶层组件中使用contextValue去包裹顶层组件,一般是根组件
<contextValue.provider value={}>
<App />
</contextValue.provider>
3.3 在子组件中使用contextValue的值
import { useContext } from 'react';
import { contextValue } from './App';
const value = useContext(contextValue);