React+TypeScript中使用Emotion

什么是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组合时后面的样式覆盖之前的样式

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值