簡介:
emotion是一個JavaScript庫,使用emotion可以用寫js的方式寫css代碼。在react中安裝emotion后,可以很方便進行css的封裝,復用。使用emotion后,瀏覽器渲染出來的標簽是會加上一個css開頭的標識。如下:截圖中以css-開頭的幾個標簽,就是使用emotion庫后渲染出來的。
下面就從安裝到使用,介紹下emotion在工程中的應用。
emotion的安裝:
1
2
|
yarn add @emotion /react yarn add @emotion /styled |
新增普通css組件:
1,命名和組件一樣,大寫字母開頭
2,styled后面跟html標簽
1
2
|
// 引入emotion import styled from "@emotion/styled”; |
1
2
3
4
5
6
7
|
// 使用emotion 創建css組件 const Container = styled.div` display: flex; flex-direction: column; align-items: center; min-height: 100vh; `; |
1
2
3
4
|
//在html代碼中使用css組件: <Container> // html代碼 </Container> |
給已存在組件加樣式:
1,變量名首字符大寫
2,將已經存在的組件作為參數傳入styled
3,樣式代碼可以加參數
1
2
3
4
5
6
7
8
9
10
|
// Card 是antd已存在的組件 const ShadowCard = styled(Card)` width: 40rem; min-height: 56rem; padding: 3.2rem 4rem; border-radius: 0.3rem; box-sizing: border-box; box-shadow: rgba(0, 0, 0, 0.1) 0 0 10px; text-align: center; `; |
1
2
3
4
5
6
7
8
9
10
|
// 引入的圖片,作為參數直接使用 import logo from "assets/logo.svg" ; // 反引號可參照魔法字符串傳入參數 const Header = styled.header` background: url(${logo}) no-repeat center; padding: 5rem 0; background-size: 8rem; width: 100%; `; |
提取公共的css組件
1, 反引號之前,接收泛型的參數, 可能用到的參數都要列出來
2, 取傳進來的參數,用props來取,比如props.between, 可以用函數返回值給css屬性賦值,css屬性不渲染,返回值就是undefined
1
|
justify-content: ${(props) => (props.between ? "space-between" : undefined)}; |
3, 可以用css選擇器
4,調用時,跟普通js組件一樣使用,傳參也相同
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
|
// 調用Row組件 <HeaderLeft gap={1}> //html代碼 </HeaderLeft> const HeaderLeft = styled(Row)``; // 定義Row組件 export const Row = styled.div<{ gap?: number | boolean; between?: Boolean; marginBottom?: number; }>` display: flex; align-items: center; justify-content: ${(props) => (props.between ? "space-between" : undefined)}; margin-bottom: ${(props) => props.marginBottom ? props.marginBottom + "px" : undefined}; > * { margin-top: 0 !important; margin-bottom: 0 !important; margin-right: ${(props) => typeof props.gap === "number" ? props.gap + "rem" : props.gap ? "2rem" : undefined}; } `; |
寫emotion行內樣式
1,在組件的頂部寫上 下面代碼,告知當前組件用了emotion行內樣式
1
|
/* @jsxImportSource @emotion/react */ |
2,行內樣式的格式:css={ /* 行內樣式代碼 */ }
1
2
3
|
<Form css={{ marginBottom: "2rem" }} layout={"inline”}> // html代碼 </Form> |
以上就是emotion的介紹和使用。(#^.^#)
以上就是React使用emotion寫css代碼的詳細內容,更多關于React用emotion寫css代碼的資料請關注服務器之家其它相關文章!
原文鏈接:https://segmentfault.com/a/1190000039778793