React - styled-components CSS套件

React - styled-components 安裝和使用

  • 安裝
  • TypeScript Button 元件,定義兩種主題
  • styled-components 的主題切換方法
  1. 先安裝套件

    1
    npm install --save styled-components
  2. 安裝 TypeScript

    1
    npm install @types/styled-components --save
  3. 新增一個 Button 元件
    如果使用 TypeScript 需要import { CSSObject },然後定義一個 MyStyle,這樣props className 才不會有問題。
    props 會有一個 theme,顏色已經定義在 themeConfig。
    詳細教學寫在註解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import React, { FunctionComponent } from 'react';
import styled, { CSSObject } from 'styled-components';

interface Props {
style?: React.CSSProperties;
children?: string;
className?: string;
theme?: 'default' | 'primary';
}

//定義 CSS 的 TypeScript
//記得import CSSObject
interface MyStyle {
config: CSSObject;
}

//定義 props 傳進來的值
const themeConfig = {
default: {
bgColor: 'transparent',
fontColor: '#000',
padding: '0',
minHeight: 'unset',
borderColor: 'transparent'
},
primary: {
bgColor: '#26815e',
borderColor: '#26815e',
fontColor: '#fff'
}
};


//如果是用 TypeScript 記得加上 FunctionComponent,這樣props className 才不會有問題。
// props 會有一個 theme,顏色已經定義在 themeConfig
const Button: FunctionComponent<Props> = (props: Props) => {
const { children, className, theme } = props;
const themeProps = theme ? themeConfig[theme] : {};

//利用ES6解構
return (
<ButtonRoot className={className} config={{ ...themeProps }}>
{children}
</ButtonRoot>
);
};

//預設
Button.defaultProps = {
theme: 'default'
};

export default Button;

//元件的一些 CSS 寫在這邊,注意:一定要用大寫
//TypeScript寫法,需要加上<MyStyle>
const ButtonRoot = styled.div<MyStyle>`
padding: ${props => props.config.padding || '10px 20px'};
background-color: ${props => props.config.bgColor};
display: inline-block;
color: ${props => props.config.fontColor};
border-radius: 8px;
cursor: pointer;
transition: 0.5s;
border: 1px solid;

//變更主題的方法
border-color: ${({ theme }) => theme.bdColor};

&:hover {
background-color: #4195ed;
}
`;
  1. 切換主題 - 新增 resources/themes/Color.tsx
    主題顏色都寫在這支檔案

    1
    2
    3
    4
    5
    6
    7
    export const lightTheme = {
    bdColor: 'transparent'
    };

    export const darkTheme = {
    bdColor: 'red'
    };
  2. 到入口App.tsx
    使用 styled-components 提供的方法 ThemeProvider,
    createGlobalStyle我把他當 Reset CSS 使用
    詳細教學寫在註解。
    注意:ThemeProvider這方法需要用在入口檔案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import styled, { createGlobalStyle, ThemeProvider } from 'styled-components';
import { lightTheme, darkTheme } from 'resources/themes/Color';

import Button from 'resources/components/atoms/Button';

interface Props {}

interface State {}

const App: FunctionComponent<Props> = (props: Props) => {
return (
<>
// 切換主題
<ThemeProvider theme={darkTheme}>
<GlobalStyle />
<Root>初始化React</Root>
<Button theme="primary">Button</Button>
</ThemeProvider>
</>
);
};

export default App;

//Reset CSS
const GlobalStyle = createGlobalStyle`
/* http://meyerweb.com/eric/tools/css/reset/
* v2.0 | 20110126
* License: none (public domain) */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline; }

/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block; }

body {
line-height: 1.5;
background-color: #E9EDED;
overflow-x: hidden;
font-family: 'Helvetica Neue', 'Microsoft JhengHei', sans-serif; }

ol, ul {
list-style: none; }

blockquote, q {
quotes: none; }

blockquote:before, blockquote:after {
content: '';
content: none; }

q:before, q:after {
content: '';
content: none; }

table {
border-collapse: collapse;
border-spacing: 0; }

*, *:before, *:after {
box-sizing: border-box; }

img {
max-width: 100%;
height: auto;
display: block; }

a {
text-decoration: none;
color: #000;
outline: none; }

button {
background-color: transparent;
outline: none;
border: 0;
font-size: 16px;
padding: 0; }
`;

心得:使用這套套件,可以快速切換主題,在一之檔案上面定義好顏色就可以切換了

文章還會繼續增加實用的技巧,先教使用主題切換,接下來會教

  1. 自行定義 RWD,如何找到下一層的 CLASS
  2. 切換主題按鈕
  3. 定義更多方法
分享到