简介:
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的介绍和应用。(#^.^#)
发表回复