React 中 Context(上下文)介绍
在 React 中,Context(上下文) 是一种用于在组件树中共享数据的机制。
历史文章
React Context API 用于在组件树中共享全局状态
React -AppVarContext.Provider 提供者组件
1.什么是 React Context?
它允许你在组件树中,不通过 props 一层层传递的情况下,直接把数据传给任意深层的子组件。
解决了“逐层传递 props”导致的代码臃肿和维护困难的问题,也叫“props drilling”。
2.Context 的组成部分
- 1.创建 Context
const MyContext = React.createContext(defaultValue);
- 2.Provider 提供数据
<MyContext.Provider value={someValue}><YourComponents />
</MyContext.Provider>
- 3.消费数据
在函数组件中使用 useContext
const value = React.useContext(MyContext);
在类组件中用 MyContext.Consumer
const ThemeContext = React.createContext('light');function App() {return (<ThemeContext.Provider value="dark"><Toolbar /></ThemeContext.Provider>);
}function Toolbar() {return <ThemedButton />;
}function ThemedButton() {const theme = React.useContext(ThemeContext);return <button style={{ background: theme === 'dark' ? 'black' : 'white' }}>按钮</button>;
}
这里,ThemedButton 虽然是深层子组件,但能直接拿到 ThemeContext 提供的值 ‘dark’,不用从 App 逐层传递。
3.总结
Context 是 React 用来跨组件共享数据的方案
避免了手动逐层传递 props
适合共享主题、用户信息、表单状态等全局或半全局数据