Skip to content

CSS-in-JS

CSS-in-JS解决方案给我们提供了新的编写CSS的方式。这些方案使用以JavaScript为基础的API来创建和编写样式。Antd5.0的css方案就是基于CSS-in-JS实现的。
好处:动态样式,元素作用域,自定义主题,支持SSR,方便单元测试等。
常见的第三方库有Styled-components,Linaria

1. 使用Styled-components

1.1 安装Styled-components

Styled-components组件的官网是https://styled-components.com,安装Styled-components

cmd
npm i styled-components

1.2 基本使用

jsx
import styled from 'styled-components'

function App() {
  // 反引号··之间添加css样式, styled.xxx, xxx其实就是具体页面标签
  const Div = styled.div`
  display: flex;
  width: 100px;
  height: 100px;
  background: red;
  margin-bottom: 10px`
  // 每个样式不能缺少分号; 
  const Button = styled(Div)`
      width: 100px;
      background-color: #f7ff00;
      // 不加& 表示给子元素加上样式
      &:hover {
          color: #f12121;
          cursor: pointer;
      }
  `
  return (
    <>
      <Div></Div>
      <Button>点击</Button>
    </>
  )
}
export default App

Alt text 使用styled(Div)表示继承Div的样式。