0%

React — Styled-component

React — Styled-component

⭐ 前言

Styled-component 是讓我們在 React 元件系統撰寫 CSS 時更加方便。
同時,也可以利用 props 動態調整樣式!

🔧 環境建置

Step1. 打開終端機安裝 create-react-app

1
npm i -g create-react-app

Step2. 建立專案資料夾名稱 react_styled

1
create-react-app react_styled

Step3. 道專案資料夾啟動專案

1
npm start

Step4. 開啟 App.js 檔案並載入 Styled-component

1
import styled from 'styled-components';

此時,我們可以利用 styled 來使用 styled-components 的方法

🚀 如何使用 Styled-component ?

重點提要

  • styled-component 的命名第一個字母要大寫
  • styled-component 要在 render 的外面 define
  • 讓我們在JSX標籤可以延續使用 element (eg:div, a, p…) 原有屬性 (eg:href, type, target…)
  • 可以使用 Templare string 讓我們方便去安插變數
  • 可以使用 props 來傳遞參數

Styled-component 的重構元件

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
function App() {
const [linkColor, setFontColor] = React.useState('#fff')

return (
<StyledApp>
<StyledHeader>
<StyledAppLogo src={logo} alt="logo" />
<StyledP>
Edit <code>src/App.js</code>!
</StyledP>
<StyledLink
href="https://google.com.tw"
target="_blank"
rel="noopener noreferrer"
fontColor={linkColor}
>
Learn React
</StyledLink>
<StyledButton buttonColor={true} onClick={() => {
linkColor === '#fff' ? setFontColor('pink') : setFontColor('#fff')
}}>Change Color</StyledButton>
<StyledButtonCool>Cool Button</StyledButtonCool>
</StyledHeader>
</StyledApp>
);
}

1️⃣ 渲染 HTML 標籤

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
  const StyledApp = styled.div`
text-align: center;
`;

const StyledHeader = styled.div`
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
`;

const StyledP = styled.p`
color: red;
background-color: black;
border-radius: 5px;
padding: 10px;
`;

const StyledButton = styled.button`
padding: 10px;
border-radius: 5px;
margin-top: 30px;
`;

2️⃣ 傳入 props 參數

範例一: 搭配三元運算子

1
2
3
4
5
6
const StyledButton = styled.button`
color: ${props => props.buttonColor ? 'purple' : '#fff '};
padding: 10px;
border-radius: 5px;
margin-top: 30px;
`;

範例二: 搭配 useState

1
2
3
const StyledLink = styled.a`
${props => `color: ${props.fontColor}`}
`;

3️⃣ 繼承元素屬性

利用 styled( )( )內為被繼承的元件

1
2
3
4
5
6
7
8
9
10
const StyledButtonCool = styled(StyledButton)`
background-color: black;
color: white;
border: 0px;
transition: all 0.3s;

&:hover {
color: red;
}
`;

4️⃣ 使用 Animations

Step1. 先載入 keyframes,才可使用方法

1
import styled, {keyframes} from 'styled-components';

Step2. 如 styled 搭配 HTML 標籤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const rotate = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;

const StyledAppLogo = styled.img`
height: 40vmin;
pointer-events: none;
animation: ${rotate} 5s linear infinite;
`;

🔎 參考資料