​emotion​​ 是一个 JavaScript库 ,使用 ​​emotion​​​ 可以用写 js 的方式写 css 代码(​​CSS in JS​​)。

在react中安装emotion后,可以很方便进行css的 封装,复用

使用emotion后,浏览器渲染出来的标签是会加上一个css开头的标识。如下:截图中以​​css-​​开头的几个标签,就是使用emotion库后渲染出来的。

CSS in JS之React-Emotion_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;

CSS in JS之React-Emotion_React-Emotion_02