在 React-Styled Components 透過 ThemeProvider 來更換網頁色彩主題樣式
Published in
5 min readMar 27, 2019
Styled-components 提供了一個
<ThemeProvider>
的外層 Component 來實踐換網站主題設計的系統。 Styled-components 使用了 React context API,讓我們想要的主題設定(像是顏色、按鈕、形狀)可以不須倚賴Props一層一層往下,在Render時直接傳到整個 App 每一個 Components 及 Styled-components。
藉由
ThemeProvider
可以簡單抽換全域所需要使用的主題樣式,像是電商要在不同節慶切換網站主題色彩,跟著活動「換皮」的遊戲網頁,都非常適合使用Styled-components來實踐。
第一步:將 ThemeProvider 從 Styled-components 中引入
import React, { Component } from 'react';
import styled from 'styled-components'
import { ThemeProvider } from "styled-components";
第二步:建立包含 Button 的 Class Component,並設定初始 Theme 為 DefaultTheme
class App extends Component {建立 包含 的 的 的 Components 初始 為 為 為 為 DefaultThemeclass App extends Component {
constructor() {
super();
this.state = {
Theme: DefaultTheme
};
}
render() {
return (
<div className="App">
<div>
<Button>Normal</Button>
<Button>Themed</Button>
</div>
</div>
);
}
}export default App;
第三 步:用 Styled-components 設定 Button
const Button = styled.div`
font-size: 1em;
margin: 1em;
padding: 0.25em 2em;
border-radius: 3px;
display: inline-block;
color: black;
border: 2px solid black;
background-color: white;
`;
並使用 props.theme
的方式來改掉顏色設定
color: ${props => props.theme.fontColor};
border: 2px solid ${props => props.theme.borderColor};
background-color: ${props => props.theme.backgroundColor};
第四 步:設定色彩主題
const DefaultTheme = {
backgroundColor: 'white',
fontColor: "#33997a",
borderColor: "#33997a"
}
const PinkTheme = {
backgroundColor: '#DB7290',
fontColor: "white",
borderColor: "#ffd7e8"
};
第五步:將 Template 中的第二顆 Button 用 <ThemeProvider></ThemeProvider>
包起來,並且設定 theme={this.state.Theme}
!!! theme 首字要小寫, 如果大寫為 Theme 會報錯
<ThemeProvider theme={this.state.Theme}>
<Button>Themed</Button>
</ThemeProvider>
存檔後即可看到被包裝過的 Theme
將 DefaultTheme 切換為 PinkTheme 即可抽換不同色彩主題
!!!補充 : ThemeProvider 裡面不能有多個 Child , 記得用一個<div></div>或<Fragment></Fragment>將 Childs 包起來
Say hello! 我是 Angel,這裏的內容如果有幫到你,希望能獲得一些拍手作為鼓勵
工作上的合作歡迎隨時透過 Mail 聯繫我 contact@aneglho.design–
Thanks for watching!