styled-components 
Styled Components 是一个用于 React 的 CSS-in-JS 库,它可以使用 JavaScript 来编写 CSS 样式.
Styled Components 通过创建 React 组件的方式来定义样式,这样可以在组件内部定义样式,而不是在全局定义样式。
它通过标记模板字面量提供了一种声明式方式来编写组件级的样式,支持动态样式、主题、服务器端渲染,并与 TypeScript 兼容,使得样式编写更直观、组件更易于维护,同时避免了全局样式冲突。
Github:https://github.com/styled-components/styled-components
安装 
bash
npm install styled-components使用 
ts
import { createGlobalStyle } from 'styled-components';
export default createGlobalStyle`
  *,
  *:before,
  *:after {
    box-sizing: border-box;
  }
`;条件渲染 
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>
    </>
  );
}扩展样式 
js
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>
    </>
  );
}使用伪类 
js
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>
    </>
  );
}参考 
Contributors 
 作者:Long Mo
 字数统计:305 字
 阅读时长:1 分钟
文章作者:Long Mo
版权声明: 本博客所有文章除特别声明外,均采用  CC BY-NC-SA 4.0  许可协议。转载请注明来自 Longmo Docs ! 
