Skip to content

Styled Components

什么是 Styled Components

Styled Components 是一个 CSS-in-JS 库,它可以使用 JavaScript 来编写 CSS 样式。

Styled Components 通过创建 React 组件的方式来定义样式,这样可以在组件内部定义样式,而不是在全局定义样式。

安装

bash
npm install styled-components

基本用法

创建 Styled Components

tsx
import styled from "styled-components";

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: #BF4F74;
`;

export default function StyledBasic() {
    return (
        <>
            <Title>Hello, React</Title>
        </>
    );
}

条件渲染

tsx
import styled from "styled-components";

const Title = styled.h1<{ $primary?: boolean }>`
    font-size: 1.5em;
    text-align: center;
    color: ${props => props.$primary ? '#BF4F74' : '#333'};
`;


export default function StyledCondition({ primary }: { primary?: boolean }) {
    return (
        <>
            <Title $primary={primary}>Hello, React</Title>
        </>
    );
}

扩展样式

tsx
import styled from "styled-components";

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: #BF4F74;
`;

const SubTitle = styled(Title)`
  font-size: 1em;
  color: #BF1F71;
`;

export default function StyledExtend() {
    return (
        <>
            <Title>Styled Title</Title>
            <SubTitle>Styled SubTitle</SubTitle>
        </>
    );
}

使用伪类

tsx
import styled from "styled-components";

const Button = styled.button`
  &:hover {
    background-color: #FF6B98;
  }

  &::before {
    content: '🚀';
    margin-right: 5px;
  }
`;

export default function StyledPsendo() {
    return (
        <>
            <Button>click</Button>
        </>
    );
}

参考