React Context
1. 何时使用 Context
export default function App () {
const [theme, setTheme] = useState('dark')
const clickHandle = () => {
if (theme === 'dark') {
setTheme('light')
} else {
setTheme('dark')
}
}
return <div>
<div onClick={clickHandle}>change theme</div>
<Parent theme={theme} />
</div>
}
function Parent ({ theme }) {
return <Child theme={theme} />
}
function Child ({ theme }) {
return <div>{theme}</div>
}2. 注意事项
3. Context.Consumer
4. 示例
4.1 动态 Context
4.2 在嵌套组件中更新 Context
4.3 嵌套的 Context
5. 过时的 API
参考文档
Last updated