React使用emotion寫css代碼
簡介:
emotion是一個JavaScript庫,使用emotion可以用寫js的方式寫css代碼。在react中安裝emotion后,可以很方便進行css的封裝,復(fù)用。使用emotion后,瀏覽器渲染出來的標簽是會加上一個css開頭的標識。如下:截圖中以css-開頭的幾個標簽,就是使用emotion庫后渲染出來的。

下面就從安裝到使用,介紹下emotion在工程中的應(yīng)用。
emotion的安裝:
yarn add @emotion/react yarn add @emotion/styled
新增普通css組件:
1,命名和組件一樣,大寫字母開頭
2,styled后面跟html標簽
// 引入emotion import styled from "@emotion/styled”;
// 使用emotion 創(chuàng)建css組件 const Container = styled.div` display: flex; flex-direction: column; align-items: center; min-height: 100vh; `;
//在html代碼中使用css組件: <Container> // html代碼 </Container>
給已存在組件加樣式:
1,變量名首字符大寫
2,將已經(jīng)存在的組件作為參數(shù)傳入styled
3,樣式代碼可以加參數(shù)
// 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;
`;
// 引入的圖片,作為參數(shù)直接使用
import logo from "assets/logo.svg";
// 反引號可參照魔法字符串傳入?yún)?shù)
const Header = styled.header`
background: url(${logo}) no-repeat center;
padding: 5rem 0;
background-size: 8rem;
width: 100%;
`;
提取公共的css組件
1, 反引號之前,接收泛型的參數(shù), 可能用到的參數(shù)都要列出來
2, 取傳進來的參數(shù),用props來取,比如props.between, 可以用函數(shù)返回值給css屬性賦值,css屬性不渲染,返回值就是undefined
justify-content: ${(props) => (props.between ? "space-between" : undefined)};
3, 可以用css選擇器
4,調(diào)用時,跟普通js組件一樣使用,傳參也相同
// 調(diào)用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行內(nèi)樣式
1,在組件的頂部寫上 下面代碼,告知當前組件用了emotion行內(nèi)樣式
/* @jsxImportSource @emotion/react */
2,行內(nèi)樣式的格式:css={ /* 行內(nèi)樣式代碼 */ }
<Form css={{ marginBottom: "2rem" }} layout={"inline”}>
// html代碼
</Form>
以上就是emotion的介紹和使用。(#^.^#)
以上就是React使用emotion寫css代碼的詳細內(nèi)容,更多關(guān)于React用emotion寫css代碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
webpack構(gòu)建react多頁面應(yīng)用詳解
這篇文章主要介紹了webpack構(gòu)建react多頁面應(yīng)用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
淺談React Native Flexbox布局(小結(jié))
這篇文章主要介紹了淺談React Native Flexbox布局(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
React為什么需要Scheduler調(diào)度器原理詳解
這篇文章主要為大家介紹了React為什么需要Scheduler調(diào)度器原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
React中實現(xiàn)父組件調(diào)用子組件的三種方法
在React中,組件之間的通信是一個常見的需求,有時,我們需要從父組件調(diào)用子組件的方法,這可以通過幾種不同的方式實現(xiàn),需要的朋友可以參考下2024-04-04

