跳至主要内容

【React】Styled-components 介紹

📌前言

Styled-components 主要是為了讓在 Styling React 時,可以也用 component 的方式,讓 CSS 更好維護。

他有幾個優點:

  • 他寫在 JSX 檔裡面,也就是說他可以跟 React components 寫在同一個檔案裡。
  • 他跟 module css 一樣有獨立的 className,不怕 className 命名重複的問題。
  • 他可以傳入 props 來動態的生成 CSS style。
  • 自動 Prefixing ,幫你在不同瀏覽器加入前綴詞。

📌使用

下載

npm install styled-components

or

yarn add styled-components

基本寫法

import styled from "styled-components";

const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: red;
`;

function App() {
return <Title>Hello World!</Title>;
}

看起來是不是很怪 XD ,從它的名字就可以知道,它把每一個 style 都變成 component ,接下來我們來一一拆解。

import styled from "styled-components";

首先先匯入 styled ,再來定義 component 名稱,因為是 component 所以第一個字也要大寫喔。

const Title = styled.h1``;

styled. 後面接的就是 HTML Tag,而 `` 裡面放的就是一般的 CSS 。


不過因為如果結構很複雜的話,一個檔案會變得很冗長,所以也可以把 styled component 另外寫一個 JS 檔,然後再匯入


可以玩玩看~

傳入參數

可以將 React 的變數傳入 Styled component ,動態生成不同情況的樣式。

import styled from "styled-components";

const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: ${(props) => (props.primary ? "red" : "blue")};
`;

function App() {
return (
<>
<Title primary={true}>I am primary</Title>
<Title primary={false}>I am secondary</Title>
</>
);
}

繼承(延伸)樣式

有時候很多 component 都有共同的樣式,例如:不同顏色的 Button,這時候就可以共用同一個 component 樣式,有繼承(延伸)的效果。

寫法就是將原本寫在 styled. 後面的 Tag 換成 (Component Name),就可以繼承(延伸) component 的 Tag 跟 style。

const Button = styled.button`
border-radius: 10rem;
border: none;
font-size: 1.2rem;
cursor: pointer;
`;

const LoginButton = styled(Button)`
background: green;
color: white;
`;

const LogoutButton = styled(Button)`
background: red;
color: black;
`;

今天就先介紹三個常用的用法,下一篇再來繼續挖掘其他的功能~~

參考

Styled-component 【Day 12】Styled-component