CSS in JS之React-Emotion
emotion
是一个 JavaScript库 ,使用emotion
可以用写 js 的方式写 css 代码(CSS in JS)。
在react中安装emotion后,可以很方便进行css的 封装,复用。
使用emotion后,浏览器渲染出来的标签是会加上一个css开头的标识。如下:截图中以css-
开头的几个标签,就是使用emotion库后渲染出来的。
安装
安装两个库:
yarn add @emotion/react
yarn add @emotion/styled
使用
1. 引入emotion
import styled from "@emotion/styled";
2. 创建css组件
// 使用emotion 创建css组件
const Container = styled.div`
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
`;
3. 在html代码中使用css组件
<Container>
// html代码
</Container>
实例
以 grid布局,实例展示 emotion
的用法:
/** @jsxImportSource @emotion/react */
import React from 'react';
import styled from "@emotion/styled"; // 1.引入emotion
import './App.css';
function App() {
// 3.提取公共的css组件
const BgColor = styled.div<{ color?: string }>`
background-color:${props => props.color ? props.color : 'initial'} ;
`
const MyBorder = styled.div<{ border?: string }>`
border:${props => props.border ? props.border + ' solid' : 'none'} ;
`
// 2.使用emotion 创建css组件
const Container = styled.div`
display: grid;
grid-template-rows: 5rem 1fr 5rem;
grid-template-columns: 10rem 1fr 10rem;
grid-template-areas:
'header header header'
'nav main aside'
'footer footer footer'
;
height: 100vh;
`
const Header = styled(BgColor)`grid-area:header`;
const Nav = styled.nav`grid-area:nav`;
const Main = styled(MyBorder)`grid-area:main`;
const Aside = styled.aside`grid-area:aside`;
const Footer = styled(BgColor)`grid-area:footer`;
return (
<div className="App">
{/* 4.在html代码中使用css组件 */}
<Container>
<Header color={'#aaa'} as='header'>header</Header>
<Nav>nav</Nav>
<Main border={'1px red'} as='main'>
<div css={{ backgroundColor: "#ccc" }}>main</div>{/* emotion行内样式 */}
</Main>
<Aside>aside</Aside>
<Footer color={'#eee'} as='footer'>footer</Footer>
</Container>
</div>
);
}
export default App;
本文作者:猫老板的豆
本文链接:https://www.cnblogs.com/bingcola/p/16499103.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」