# 【Lidemy】Week 21 前端框架(一)--Styled Component #### 基礎用法 參考文件:[Basics](https://styled-components.com/docs/basics) * `const 元件名稱 = styled.標籤名稱`:把 CSS 寫成 component 的感覺 ``` const Description = styled.p` color: red; padding: 20px; border: 1px solid black; ` ``` * `const 元件名稱 = styled(已存在的 style component)`:擴張 style,在 styled 元件再加上 style ``` const RedButton = styled(Button)` color: pink; `; ``` * `props => props.參數名稱 ? value1 : value2`:用 function 決定 style 的值 ``` const Button = styled.button` background: ${props => props.primary ? "palevioletred" : "white"}; ` <Button>Normal</Button> <Button primary>Custom Button</Button> ``` * `<component as="">`:改變元素的標籤 ``` <Button>Normal</Button> <Button as="a" href="/">Primary</Button> ``` * `props.自訂屬性`:在 styled component 自訂屬性,再把值寫到 react component 裡面 ``` const Button = styled.button` background: palevioletred; color: ${props => props.buttonColor || "white"}; ` <Button>Normal</Button> <Button buttonColor="rebeccapurple">Custom Button</Button> ``` * 在 style component 開頭加上 Styled,區分 react component ``` const StyledCounter = styled.div`` ``` * 在 render 的元件外面定義 styled component,不要定義在裡面 ``` const StyledWrapper = styled.div` /* ... */ ` const Wrapper = ({ message }) => { return <StyledWrapper>{message}</StyledWrapper> } ``` * `styled(已知的 styled component).attrs`:重複利用 style 的屬性 ``` const Input = styled.input.attrs(props => ({ type: "text", size: props.size || "1em", })) const PasswordInput = styled(Input).attrs({ type: "password", })` ``` * 使用 keyframes ``` // 先引入 keyframes import styled, { keyframes } from 'styled-components'; // 寫 keyframe const rotate = keyframes` from { transforom: rotate(0deg); } to { transform: rotate(360deg); } ` // 帶入 animation const Rotate = styled.div` display: inline-block; animation: ${rotate} 2s linear infinite; padding: 2rem 1rem; font-size: 1.2rem; `; ``` #### 選擇器 `&:hover`:元件被 hover 時 `& ~ &`:元件同層元件(兄弟元素) `& + &`:元件正旁邊的元件 `&.something`:元件且有 class 為 something 的元件 `.something &`:在 .something 裡面的元件