当前位置: 首页 > Web前端 > CSS

最好在react项目中写css代码--emotion

时间:2023-03-30 17:24:39 CSS

简介:emotion是一个JavaScript库,使用emotion可以像写js的方式写css代码。在react中安装emotion后,打包复用css非常方便。使用emotion后,浏览器渲染的标签会添加一个css开头的logo。如下:截图中css-开头的标签是使用情感库渲染后的效果。下面将从安装到使用介绍情感在工程中的应用。情感安装:yarnadd@emotion/reactyarnadd@emotion/styled添加常用的css组件:1、名称与组件相同,以大写字母开头2、styled后跟html标签//importemotionimportstyledfrom"@emotion/styled";//使用emotion创建css组件constContainer=styled.div`display:flex;flex-direction:column;align-items:center;min-height:100vh;`;//在css组件中使用html代码://html代码给已有组件添加样式:1、变量名首字符大写2、将已有组件作为参数传入styled3,样式代码可以添加参数//Cardis现有的antd组件constShadowCard=styled(Card)`width:40rem;最小高度:56rem;填充:3.2rem4rem;边界半径:0.3rem;框大小:边框框;盒子阴影:rgba(0,0,0,0.1)0010px;text-align:center;`;//导入的图片可以直接作为参数importlogofrom"assets/logo.svg";//反引号可以参考魔术字符串传入参数constHeader=styled.header`background:url(${logo})no-repeatcenter;padding:5rem0;background-size:8rem;width:100%;`;提取常用css组件1、在反引号之前,接收Generic参数,可能用到的参数一定要列出来2、取传入的参数,使用props获取,比如props.between,可以使用函数返回值赋值给css属性赋值,css属性不渲染,返回值为undefinedjustify-content:${(props)=>(props.between?"space-between":undefined)};3、可以使用cssselector4、调用时和普通js组件一样使用,参数相同//调用Row组件//html代码constHeaderLeft=styled(Row)``;//定义Row组件exportconstRow=styled.div<{gap?:number|布尔值;之间?:布尔值;marginBottom?:number;}>`display:flex;align-items:center;justify-content:${(props)=>(props.between?"space-between":undefined)};margin-bottom:${(道具)=>道具.marginBottom?props.marginBottom+"px":undefined};>*{margin-top:0!important;margin-bottom:0!important;margin-right:${(props)=>typeofprops.gap==="数字“?props.gap+"rem":props.gap?“2rem”:未定义};}`;编写emotion内联样式1、在组件顶部写入如下代码,告知当前组件使用Emotion内联样式/*@jsxImportSource@emotion/react*/2,内联样式格式:css={/*inline样式代码*/}//html代码以上就是情感的介绍和使用(#^.^#)