在react项目中编写css,更好的在react项目中写css代码--emotion
簡介:
emotion是一個JavaScript庫,使用emotion可以用寫js的方式寫css代碼。在react中安裝emotion后,可以很方便進行css的封裝,復用。使用emotion后,瀏覽器渲染出來的標簽是會加上一個css開頭的標識。如下:截圖中以css-開頭的幾個標簽,就是使用emotion庫后渲染出來的。
下面就從安裝到使用,介紹下emotion在工程中的應用。
emotion的安裝:yarn add @emotion/react
yarn add @emotion/styled
新增普通css組件:
1,命名和組件一樣,大寫字母開頭
2,styled后面跟html標簽// 引入emotion
import styled from "@emotion/styled”;// 使用emotion 創建css組件
const Container = styled.div`
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
`;//在html代碼中使用css組件:
// html代碼
給已存在組件加樣式:
1,變量名首字符大寫
2,將已經存在的組件作為參數傳入styled
3,樣式代碼可以加參數// 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;
`;// 引入的圖片,作為參數直接使用
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屬性不渲染,返回值就是undefinedjustify-content: ${(props) => (props.between ? "space-between" : undefined)};
3, 可以用css選擇器
4,調用時,跟普通js組件一樣使用,傳參也相同// 調用Row組件
//html代碼
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行內樣式/* @jsxImportSource @emotion/react */
2,行內樣式的格式:css={ /* 行內樣式代碼 */ }
// html代碼
以上就是emotion的介紹和使用。(#^.^#)
總結
以上是生活随笔為你收集整理的在react项目中编写css,更好的在react项目中写css代码--emotion的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java实验_Java实验报告(实验一)
- 下一篇: mysql 出现 quot_MYSQL