在hooks我覺得useContext變得更複雜了,並沒有因為hooks而變簡單,原先的props反而很單純。
官方範例
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>
);
}
有時候我都覺得官方的範例都寫得很有藝術,要靜下心慢慢看才看得懂
於是我都很懶...直接放到實例跑一次畫面大概知道是在做甚麼。
改寫成
import React, {useContext} from 'react'
const themes = {
light: {
foreground: "#000000",
background: "#eeeeee"
},
dark: {
foreground: "#ffffff",
background: "#222222"
}
};
const ThemeContext = React.createContext(themes.light);
function ThemedButton(props) {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}
export default function App() {
return (
<ThemeContext.Provider value={themes.dark}>
<ThemedButton />
</ThemeContext.Provider>
);
}
因為props能應用的地方太廣太重要,這部分要慢慢的累積
這裡useContext有幾個重要的地方要注意
const theme = useContext(ThemeContext); //定義useContext
const XXX = React.createContext(themes.light); //宣告XXX 預設themes.light
<XXX.Provider></XXX.Provider> //輸出固定寫法
createContext跟Provider是互相對應的,這裡要背起來,他是不能改變的