什么是Emotion?
一个css in js框架
Emotion 是一个专为使用 JavaScript 编写 css
样式而设计的库。除了通过源映射、标签和测试实用程序等功能提供出色的开发人员体验之外,它还提供强大且可预测的样式组合。支持字符串和对象样式。
安装
yarn add @emotion/react
yarn add @emotion/react @emotion/styled
行内样式
/* @jsxImportSource @emotion/react */
import React from 'react';
import { jsx, css} from '@emotion/react';
function App() {
return (
<div className="App">
<h1 css={css`
color:red;
`}>
测试
</h1>
</div>
);
}
export default App;
这里必须要使用/* @jsxImportSource @emotion/react */
而不是官网的/** @jsx jsx */
具体原因可以查看这个大佬的文章@emotion在React17的适配问题(@jsxImportSource/@jsxRuntime的作用)我没必要搬过来了。
增加样式组件
/* @jsxImportSource @emotion/react */
import React from 'react';
import { jsx, css} from '@emotion/react';
import styled from '@emotion/styled';
const AppWrapper = styled.div`
width:100px;
height:100px;
background:red;
`
function App() {
return (
<div className="App">
<AppWrapper>123</AppWrapper>
</div>
);
}
export default App;
props传参
/* @jsxImportSource @emotion/react */
import React,{FC } from 'react';
import styled from '@emotion/styled';
interface StyledComponentProps {
bgColor: string
}
interface ComponentProps {
className?: string
label: string
}
const Component: FC<ComponentProps> = ({
label,
className
}) => <div className={className}>{label}</div>
const StyledComponent0 = styled(Component)<StyledComponentProps>`
color: red;
background: ${props => props.label ? props.bgColor : 'white'};
`
function App() {
return (
<div className="App">
<StyledComponent0
bgColor="blue"
label="测试"
/>
</div>
);
}
export default App;
多个样式类单独生成
/* @jsxImportSource @emotion/react */
import React,{FC } from 'react';
import {cx, css} from '@emotion/css'
const styleTextColor = css`
color:red;
`
const styleFontSize = css`
font-size:15px;
`
function App() {
return (
<div className="App">
<div className={`${cx(styleTextColor)} ${cx(styleFontSize)}`}>测试</div>
</div>
);
}
export default App;
多个样式合并到一个样式类
/* @jsxImportSource @emotion/react */
import React,{FC } from 'react';
import {css} from '@emotion/react'
const styleTextColor = css`
color:red;
`
const styleFontSize = css`
font-size:15px;
`
function App() {
return (
<div className="App">
<div css={[styleTextColor,styleFontSize]}>测试</div>
</div>
);
}
export default App;
总结
‘@emotion/css’ 利用cx返回生成的类名字符串
‘@emotion/react’ 中css返回对象
CX组合时后面的样式覆盖之前的样式