介绍 useContext
前,我们必须先认识 Context
。
Context
概念有点像是 React
的全域变数概念,像是使用者登入状态、样式等等。
根据官方文件写道,它会接受一个 context object
(React.createContext 的回传值)并回传该 context 目前的值。
context object
:const value = useContext();
const { Provider, Consumer } = value ;
const themes = {
light: {
foreground: "#000000",
background: "#eeeeee"
},
dark: {
foreground: "#ffffff",
background: "#222222"
}
};
const ThemeContext = React.createContext(themes.light);
function App() {
return (
<ThemeContext.Provider value={themes.dark}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar(props) {
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>
);
}
useContext
的参数必需为 context object 自己:
useContext(MyContext)
<<: [Day23] - 介绍 Stencil.js 如何使用
>>: 【在厨房想30天的演算法】Day 12 资料结构:杂凑表 Hash Table
虽然说大家练演算法都提 Leetcode, 但不同平台也有各自的特色, 这里就我的使用心得来提一下。...
量化交易30天 本系列文章是纪录一位量化交易新手的学习过程,除了基础的Python语法不说明,其他...
这一篇与[day 26]的差异是,我们对於对於训练模型上参数的调整。 可以先看一下原始资料集,是之前...
本文将於赛後同步刊登於笔者部落格 有兴趣学习更多 Kubernetes/DevOps/Linux 相...
後端 side project 就是要 泛舟 部落格啊,不然要干嘛 照官方教学做一个基本的 CRUD...