React使用emotion写css代码
导读:收集整理的这篇文章主要介绍了React使用emotion写css代码,觉得挺不错的,现在分享给大家,也给大家做个参考。 目录@H_360_2@简介:emotion的安装:新增普通css组...
收集整理的这篇文章主要介绍了React使用emotion写css代码,觉得挺不错的,现在分享给大家,也给大家做个参考。 目录@H_360_2@- 简介:
- emotion的安装:
- 新增普通css组件:
- 给已存在组件加样式:
- 提取公共的css组件
- 写emotion行内样式
简介:
emotion是一个JavaScript库,使用emotion可以用写js的方式写css代码。在react中安装emotion后,可以很方便进行css的封装,复用。使用emotion后,浏览器渲染出来的标签是会加上一个css开头的标识。如下:截图中以css-开头的几个标签,就是使用emotion库后渲染出来的。
下面就从安装到使用,介绍下emotion在工程中的应用。
emotion的安装:
yarn add @emotion/reactyarn add @emotion/styled
新增普通css组件:
1,命名和组件一样,大写字母开头
2,styled后面跟htML标签
// 引入emotionimport 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的介绍和使用。(#^.^#)
以上就是React使用emotion写css代码的详细内容,更多关于React用emotion写css代码的资料请关注其它相关文章!
您可能感兴趣的文章:- 详解react的两种动态改变css样式的方法
- 基于react项目打包css引用路径错误解决方案
- react使用CSS实现react动画功能示例
- react中使用css的7中方式(最全总结)
- 在Create React App中使用CSS Modules的方法示例
- 在create-react-app中使用css modules的示例代码
- 详解使用create-react-app添加css modules、sasss和antd
- ReactJs设置css样式的方法
- 如何用react优雅的书写CSS
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: React使用emotion写css代码
本文地址: https://pptw.com/jishu/595137.html
