昨天介紹了context是什麼,以及useContext要怎麼用,今天來介紹一下要怎麼在開發上實際運用context object以及useContext。
首先先建立我們要用的幾個元件及樣式:
const SingleCard = ()=>{
return (
<Col>
<Card style={theme}>
<Card.Body>
<Card.Title>This is Title</Card.Title>
<Card.Text>
this is a example card, for showing how to use Context.
</Card.Text>
<Card.Link>A link</Card.Link>
</Card.Body>
</Card>
</Col>
)
}
const Cards = ()=>{
return (
<Row className="h-100 justify-content-between align-items-center">
<SingleCard />
<SingleCard />
<SingleCard />
</Row>
)
}
const Page = ({children})=>{
return (
<Container className="vh-100">
{children}
</Container>
)
}
const App = ()=>{
return (
<div>
<Page>
<Cards/>
</Page>
</div>
)
}
整體架構長這樣:
畫面:
接著,在元件外建立要使用的樣式theme object:
const theme = {
light: {
backgroundColor: "white",
color: "black"
},
dark: {
backgroundColor: "black",
color: "white"
}
}
然後為了把theme傳進裡面的元件,要建立context object,並設定預設值為theme.light:
const themeContext = createContext(theme.light);
若是有元件在Provider外使用context object,就會使用到預設值的樣式。
接著設定Provider的元件:
const ThemeProvider=({children})=>{
return (
<themeContext.Provider value={theme}>
{children}
</themeContext.Provider>
)
}
為方便取得,我們直接將ThemeProvider包在App外面:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<div>
<ThemeProvider>
<App/>
</ThemeProvider>
</div>
)
為了方便使用useContext(),在元件外面再寫一個函式,並return回useContext()函式:
const useTheme = ()=>{
return useContext(themeContext);
}
接著,在要使用的元件中使用useTheme,取得theme。先在SingleCard中設定一個條件控制,如果isLight是true就設定theme為light,否則為dark:
const SingleCard = ({isLight})=>{
let theme = useTheme();
if(isLight){
theme = theme.light;
}else{
theme = theme.dark;
}
return (
<Col>
<Card style={theme}>
{/*...*/}
</Card>
</Col>
)
}
並在Cards設定是true還是false:
const Cards = ()=>{
return (
<Row className="h-100 justify-content-between align-items-center">
<SingleCard isLight={false}/>
<SingleCard isLight={true}/>
<SingleCard isLight={false}/>
</Row>
)
}
這樣就成功使用了context object,在沒有傳遞props的情況下拿到最外層的theme。
這樣的做法也可以用在登入與否的條件判斷,取得外層的token物件,判斷有沒有東西,有的話就render,沒有的話就跳轉等。
範例程式碼:codepen