关于react.js:更好的在react项目中写css代码emotion

8次阅读

共计 1836 个字符,预计需要花费 5 分钟才能阅读完成。

简介:

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 组件:<Container>
// html 代码
</Container>

给已存在组件加款式:

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 属性不渲染,返回值就是undefined

justify-content: ${(props) => (props.between ? "space-between" : undefined)};

3, 能够用 css 选择器
4,调用时,跟一般 js 组件一样应用,传参也雷同

// 调用 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 行内款式

/* @jsxImportSource @emotion/react */

2,行内款式的格局:css={/* 行内款式代码 */}

<Form css={{marginBottom: "2rem"}} layout={"inline”}>
// html 代码
</Form>

以上就是 emotion 的介绍和应用。(#^.^#)

正文完
 0