useContext就是vue的provide/inject
通常,当我们需要将数据从父组件传递到子组件时,我们使用 props。想象一下这样的结构:你有一些深嵌套的组件,而你只需要来自深嵌套子组件中父组件的某些内容。在这种情况下,你仍然需要将 prop 传递到整个组件链中,这可能会很烦人。
Context 设计目的是为了共享那些对于一个组件树而言是“全局”的数据,例如当前认证的用户、主题或首选语言。举个例子,在下面的代码中,我们通过一个 “theme” 属性手动调整一个按钮组件的样式。
useContext示例
import React, { useContext, useState } from "react";const ThemeContext = React.createContext();function App() {const [themes, setThemes] = useState({value: {foreground: "#000000",background: "#eeeeee",},});return (<ThemeContext.Provider value={themes.value}><Toolbar /><buttononClick={() => {setThemes({value: {foreground: "#ffffff",background: "#222222",},});}}>click black</button></ThemeContext.Provider>);}function Toolbar() {return (<div><ThemedButton /></div>);}function ThemedButton() {const theme = useContext(ThemeContext);return (<button style={{ background: theme.background, color: theme.foreground }}>I am styled by theme context!</button>);}export default App;
https://react.docschina.org/docs/context.html#reactcreatecontext
https://v3.cn.vuejs.org/guide/component-provide-inject.html#%E5%A4%84%E7%90%86%E5%93%8D%E5%BA%94%E6%80%A7
在class组件中使用context
static contextType = MyContext; // 声明使用的context后,就可以使用this.context.属性访问MyContext中的属性
this.context.store
