styled-components 库的用法介绍和实践总结

王柳  金牌会员 | 2024-8-19 04:01:06 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 539|帖子 539|积分 1617

styled-components 库的实践用法总结

前言

前段时间开发了一个 NiceTab 欣赏器插件,并写了一篇介绍文章,新开发了一款欣赏器Tab管理插件,OneTab 的升级更换品, 欢迎品尝!。
在插件中用到了 styled-components 这个库,于是做一个基本的介绍和分享。
在开发 NiceTab 插件时,只是一些粗浅的利用,整理完这篇利用条记后,我准备优化一波了。
styled-components 库介绍

什么是 styled-components

styled-components 是一个流行的 CSS-in-JS 库, 它允许您在 JavaScript 中编写 CSS 样式,是 CSS-in-JS 方案中的一种实现方式。
   styled-components is the result of wondering how we could enhance CSS for styling React component systems. By focusing on a single use case we managed to optimize the experience for developers as well as the output for end users.
  

  • 官方文档: 官方文档
  • Github: Github
为什么要利用 styled-components

我们看看官网介绍:


  • Automatic critical CSS - 主动关键CSS: 完全主动地跟踪页面上呈现的组件并注入它们的样式。结合代码分割,按需加载。
  • No class name bugs - 不存在类名冲突问题: 生成唯一的类名。不消担心类名重复、冲突、覆盖以及拼写错误等问题。
  • Easier deletion of CSS - 便于样式剔除: 传统的编写样式方式很难检测样式和类名是否被利用。而 styled-components 会与特定的组件关联,在工程化项目中,构建工具可以轻易的检测到样式组件是否被利用,未被利用的样式组件会被剔除,避免无用代码打包到构建产物中。
  • Simple dynamic styling - 易于编写动态样式: styled-components 样式组件可以根据 props 和全局主题来动态调解样式,无需手动管理众多样式类。
  • Painless maintenance - 便于维护: 不须要查找众多文件来排查组件样式,降低维护本钱。
  • Automatic vendor prefixing - 主动添加厂商前缀: 您只须要编写标准的 CSS 样式,其他的事情 styled-components 主动帮您处理。
传统 CSS 方式的缺点


  • 缺乏作用域,全局样式污染,容易出现类名冲突,样式覆盖问题,出现问题难以排查。须要通过 namespace 命名空间、书写顺序、优先级等方式来缓解。
  • 原生 CSS 在没有 scss,less 等预处理器的情况下,编写起来非常痛苦。
  • 实现动态样式,须要预先界说多个类名,为不同类目编写对应的样式,然后根据情况动态绑定不同的类名。
开发中感受


  • 编写一个功能组件,大概只须要添加少许样式 (现在的项目大多都会利用 UI 组件库,自带各种样式),为此而创建一个 css 文件不划算,还大概会有全局样式污染。只须要在该功能组件中界说一个 styled-components 样式组件即可。
  • 在 html 标签元素书写行内样式大概绑定 style 变量都难以界说伪类样式和复杂选择器(如::hover, :before, :after, :first-child, &选择器, +选择器等等)
  • 如果编写的功能组件须要编写的样式比较多,可以抽取到一个 js 或 ts 文件中,然后引入即可,由于 styled-components 界说的都是 js 对象。
  • 支持 scss 风格的语法。
  • 快速定位样式界说代码:传统的方式,须要全局搜索元素类名,才华定位到样式代码。而 js 方式的界说,编辑器能快速跳转定位。
styled-components 的缺点:


  • 生成的类名是一串 hash 值, 会绑定到对应的 dom 标签上,难以定位元素,建议给 styled-components 样式组件都添加一个 class 样式名,便于辨认。
  其他 css-in-js 方案

利用 css-in-js 方案的库,比较常见的另有 emotion 和 jss, 各人可以自行实验利用。
styled-components 的基本利用

安装



  • npm 安装:npm install styled-components
  • pnpm 安装:pnpm add styled-components
  • yarn 安装:yarn add styled-components
   如果您利用像 yarn 这种支持 package.json 的 resolutions 字段的包管理器,剧烈建议您向此中添加一个与主版本对应的入口配置。这有助于避免因项目中安装了多个版本的 styled-components 而引起的一系列问题。
  基本用法

   参考链接:getting-started
  先上一个示例:
  1. import styled from "styled-components";
  2. // 创建一个 Title 样式组件,使用 <h1> 标签
  3. const Title = styled.h1`
  4.   font-size: 24px;
  5.   text-align: center;
  6.   color: #fff;
  7. `;
  8. // 创建一个 Wrapper 样式组件,使用 <section> 标签
  9. const Wrapper = styled.section`
  10.   padding: 30px;
  11.   background: #000;
  12. `;
  13. // 在 jsx 中使用
  14. export default function App() {
  15.   return (
  16.     <Wrapper>
  17.       <Title>Hello World!</Title>
  18.     </Wrapper>
  19.   );
  20. }
复制代码
利用起来挺简单的,除了上面示例中的 h1 和 section 标签,你还可以根据情况利用其他 html 标签。
SCSS 风格语法

你可以像编写 SCSS 样式一样,编写 styled-components 的样式, 比如选择器嵌套、伪类样式、各种选择器语法等
  1. import styled from "styled-components";
  2. // 创建一个 Wrapper 样式组件,使用 <section> 标签
  3. const Wrapper = styled.section`
  4.   padding: 30px;
  5.   background: #000;
  6.   .text {
  7.     color: #fff;
  8.     &.red {
  9.       color: red;
  10.     }
  11.   }
  12.   button {
  13.     color: #333;
  14.     &:hover {
  15.       color: blue;
  16.     }
  17.     & + button {
  18.       margin-left: 10px;
  19.     }
  20.   }
  21. `;
  22. // 在 jsx 中使用
  23. export default function App() {
  24.   return (
  25.     <Wrapper>
  26.       <div className="text"> Hello World! </div>
  27.       <div className="text red"> Good good study, day day up! </div>
  28.       <button>取消</button>
  29.       <button>确定</button>
  30.     </Wrapper>
  31.   );
  32. }
复制代码
另有一个比较厉害的功能 &&,它可以指向当前样式组件的实例,这在复杂的样式逻辑中非常实用。这个各人可以直接参考官方示例-&&会比较清晰。
  1. const Input = styled.input.attrs({ type: "checkbox" })``;
  2. const Label = styled.label`
  3.   align-items: center;
  4.   display: flex;
  5.   gap: 8px;
  6.   margin-bottom: 8px;
  7. `
  8. const LabelText = styled.span`
  9.   ${(props) => {
  10.     switch (props.$mode) {
  11.       case "dark":
  12.         return css`
  13.           background-color: black;
  14.           color: white;
  15.           ${Input}:checked + && {
  16.             color: blue;
  17.           }
  18.         `;
  19.       default:
  20.         return css`
  21.           background-color: white;
  22.           color: black;
  23.           ${Input}:checked + && {
  24.             color: red;
  25.           }
  26.         `;
  27.     }
  28.   }}
  29. `;
  30. export default function App() {
  31.   return (
  32.     <React.Fragment>
  33.       <Label>
  34.         <Input defaultChecked />
  35.         <LabelText>Foo</LabelText>
  36.       </Label>
  37.       <Label>
  38.         <Input />
  39.         <LabelText $mode="dark">Foo</LabelText>
  40.       </Label>
  41.       <Label>
  42.         <Input defaultChecked />
  43.         <LabelText>Foo</LabelText>
  44.       </Label>
  45.       <Label>
  46.         <Input defaultChecked />
  47.         <LabelText $mode="dark">Foo</LabelText>
  48.       </LabelText>
  49.     </React.Fragment>
  50.   )
  51. }
复制代码
上面代码示例摘取自官方示例,此中的 && 就代表 LabelText 组件实例
${Input}:checked + && { color: red; } 表示 选中状态的 checkbox 紧邻的 LabelText 的文字颜色为红色。
命名规范建议

为了统一代码规范,让代码逻辑一目了然。提供几点建议


  • styled-components 创建的样式组件以 StyledXXX 格式举行命名,以便和常规的功能组件区分开来,比如 StyledTodoList。
  • 一个功能组件中,styled-components 样式组件不多的话,可以直接在当前功能组件中界说并利用。如果界说的样式组件比较多,建议将样式组件单独提取到一个文件。
  • 提取的样式组件的文件名统一格式为 xxx.styled.js, typescript 项目则利用 xxx.styled.ts, 比如 TodoList.tsx 功能组件, 对应的样式文件则为 TodoList.styled.ts。
固然,不一定非要上面的格式命名,只要制定一个统一的规范即可。
  1. // TodoList 组件
  2. import styled from "styled-components";
  3. // TodoListItem 是 React 功能组件
  4. import TodoListItem from './TodoListItem';
  5. const StyledTodoList = styled.ul`
  6.   broder: 1px solid #999;
  7.   // ...
  8. `;
  9. export default function TodoList() {
  10.   return (
  11.     <StyledTodoList>
  12.       <TodoListItem />
  13.       <TodoListItem />
  14.     </StyledTodoList>
  15.   )
  16. }
复制代码
统一规范之后,一眼就能分辨出,StyledTodoList 是界说的样式组件(界说样式),而 TodoListItem 是功能组件,处理功能和交互逻辑。
另外须要注意的是:记得在 React 组件渲染方法之外界说样式组件,否则将会在每次 render 时重新创建。
剧烈推荐:
  1. // 推荐方式
  2. const StyledButton = styled.button`
  3.   color: #333;
  4. `;
  5. const App = ({ text }) => {
  6.   return <StyledButton>{text}</StyledButton>
  7. };
复制代码
不建议:
  1. const App = ({ text }) => {
  2.   const StyledButton = styled.button`
  3.     color: #333;
  4.   `;
  5.   return <StyledButton>{text}</StyledButton>
  6. };
复制代码
传递 props 参数

   参考链接:adapting-based-on-props
  styled-components 创建的组件就是个组件对象,你可以像利用 React 组件一样利用它们。
对于组件来说,props 传参至关重要,可以动态调解逻辑和样式。
  1. import styled from "styled-components";
  2. // 基础按钮
  3. const StyledBaseButton = styled.button`
  4.   background: ${props => props.$bgColor || '#fff'};
  5.   color: ${props => props.$color || '#333'};
  6. `;
  7. export default function BaseButton() {
  8.   return (
  9.     <div>
  10.       <StyledBaseButton>取消</StyledBaseButton>
  11.       <StyledBaseButton $bgColor="blue" $color="#fff">确定</StyledBaseButton>
  12.     </div>
  13.   )
  14. }
复制代码
下面我们看一个 typescript 的示例:
  1. import styled from "styled-components";
  2. // 基础按钮
  3. const StyledBaseButton = styled.button<{ $bgColor?: string; $color?: string; }>`
  4.   background: ${props => props.$bgColor || '#fff'};
  5.   color: ${props => props.$color || '#333'};
  6. `;
复制代码
在 typescript 项目中,会根据类型界说检测组件上绑定的 props 属性,错传、漏传、多传都会举行提示。
样式继承和扩展

   参考链接:extending-styles
  我们想要在一个样式组件的底子上扩展其他样式,只须要利用 styled() 包裹,然后添加所需样式即可,比方:
  1. import styled from "styled-components";
  2. // 基础按钮
  3. const StyledBaseButton = styled.button<{ $bgColor?: string; $color?: string; }>`
  4.   background: ${props => props.$bgColor || '#fff'};
  5.   color: ${props => props.$color || '#333'};
  6. `;
  7. // 边框按钮const StyledBorderButton = styled(StyledBaseButton)<{$borderColor?: string}>`  border: 1px solid ${props => props.$borderColor || '#ccc'};`;export default function App {  return (    <StyledBorderButton $borderColor="#999"></StyledBorderButton>  )}
复制代码
如许就可以在底子样式组件上扩展其他样式,用来承接业务逻辑。
有些时候,我们想复用底子样式组件,但是 底子样式组件的 html 元素标签类型又不适用,这种情况可以利用 as 属性来动态更换底子样式组件的元素标签。
下面示例,是复用 StyledBaseButton 的样式,并将 button 标签更换为 a 标签。
  1. import styled from "styled-components";
  2. // 基础按钮
  3. const StyledBaseButton = styled.button<{ $bgColor?: string; $color?: string; }>`
  4.   background: ${props => props.$bgColor || '#fff'};
  5.   color: ${props => props.$color || '#333'};
  6. `;
  7. export default function App {  return (    <StyledBorderButton as="a" href="https://example.com" $bgColor="blue" $color="#fff"></StyledBorderButton>  )}
复制代码
界说公共样式

我们经常会有利用公共样式的场景,比如 ellipsis 来实现文字超长省略。
  1. overflow: hidden;
  2. text-overflow: ellipsis;
  3. white-space: nowrap;
复制代码
这种场景非常多,没须要在每个地方都写一遍上面的这一段代码,这时候可以利用 styled-components 导出的 css 函数可以生成一个公共样式组件, 建议单独创建一个样式文件存放公共样式。
我们创建一个 Common.styled.ts 文件:
  1. // Common.styled.ts
  2. import styled, { css } from "styled-components";
  3. export const StyledCommonEllipsis = css`
  4.   overflow: hidden;
  5.   text-overflow: ellipsis;
  6.   white-space: nowrap;
  7. `;
  8. // ......
复制代码
然后在 Title.tsx 组件中利用:
  1. // Title.tsx
  2. import styled from "styled-components";
  3. import { StyledCommonEllipsis } from '@/common/styled/Common.styled.ts'
  4. const StyledTitle = styled.div`
  5.   width: 300px;
  6.   color: #333;
  7.   ${StyledEllipsis};
  8. `;
  9. export default function App() {
  10.     return <StyledTitle>这是很长的一段文字标题这是很长的一段文字标题这是很长的一段文字标题</StyledTitle>
  11. }
复制代码
上面这种方式是通过引用公共样式组件实现的,还可以直接利用原始的方式来界说一个公共class样式,全局引入公共样式,然后在元素标签上利用class名即可。
  1. /* common.css */
  2. .ellipsis {
  3.   overflow: hidden;
  4.   text-overflow: ellipsis;
  5.   white-space: nowrap;
  6. }
复制代码
  1. /* Title.tsx */
  2. export default function App() {
  3.     return <StyledTitle className="ellipsis">这是很长的一段文字标题</StyledTitle>
  4. }
复制代码
全局样式

   参考链接:createglobalstyle
  注意:版本要求 v4 以上,web-only.
通过 createGlobalStyle 方法也可以注入全局公共样式。
  1. import { createGlobalStyle } from 'styled-components';
  2. const GlobalStyle = createGlobalStyle<{ $whiteColor?: boolean; }>`
  3.   body {
  4.     color: ${props => (props.$whiteColor ? 'white' : 'black')};
  5.   }
  6.   .ellipsis {
  7.     overflow: hidden;
  8.     text-overflow: ellipsis;
  9.     white-space: nowrap;
  10.   }
  11. `;
  12. export default function App() {
  13.   return <React.Fragment>
  14.     <GlobalStyle $whiteColor />
  15.     <Navigation />
  16.   </React.Fragment>
  17. };
复制代码
适用 React 组件

   参考链接:styling-any-component
  styled 方法可以在任何 React 组件上完美运行,只须要给组件传递 className 属性,并在组件内的 dom 元素上绑定该 className 属性即可。
  1. import styled from "styled-components";
  2. // TodoList 组件
  3. const TodoList = ({ className, children }) => (
  4.   <ul className={className}>
  5.     <li>
  6.       <checkbox></checkbox>
  7.       <span>待办项</span>
  8.     </li>
  9.   </ul>
  10. );
  11. // 横向 inline 布局
  12. const StyledTodoList = styled(TodoList)`
  13.   display: flex;
  14.   align-items: center;
  15.   li {
  16.     display: flex;
  17.     align-items: center;
  18.     padding: 8px 16px;
  19.   }
  20. `;
  21. export default function App {
  22.   return (
  23.     <TodoList></TodoList>
  24.     <StyledTodoList></StyledTodoList>
  25.   )
  26. }
复制代码
如许就可以改变组件的内部样式了。
attrs 属性设置

   参考链接:attaching-additional-props
  有些元素标签自带部分属性,比如 input 元素 的 type 属性有 text|email|color|file|radio|checkbox 等等类型,我们在利用时须要手动设置这些属性。
再比如常用的 button 按钮的 type 属性有 button|submit|reset 这些类型。
利用 .attrs 方法,我们可以预设一些属性,并且根据情况动态修改这些属性。
  1. import styled from "styled-components";
  2. const StyledInput = styled.input.attrs(props => ({
  3.   type: props.type || 'text'
  4. }))`
  5.   color: '#333';
  6.   font-size: 14px;
  7. `;
  8. const StyledFileInput = styled.input.attrs({ type: 'file' })`
  9.   width: 40px;
  10.   height: 40px;
  11.   border-radius: 50%;
  12. `;
  13. const StyledButton = styled.button.attrs(props => ({
  14.   type: props.type || 'button'
  15. }))`
  16.   border: none;
  17.   outline: none;
  18.   background: blue;
  19.   color: #fff;
  20. `;
  21. export default function App {
  22.   return (
  23.     <div>
  24.       <StyledInput></StyledInput>
  25.       <StyledInput type="email"></StyledInput>
  26.       <StyledInput type="password"></StyledInput>
  27.       <StyledFileInput></StyledFileInput>
  28.       <StyledButton></StyledButton>
  29.       <StyledButton type="submit"></StyledButton>
  30.     </div>
  31.   )
  32. }
复制代码
动画特性

   参考链接:animations
  我们可以在某个样式组件中利用 @keyframes 来界说动画帧,来避免全局冲突。
[code]import { keyframes } from 'styled-components';

const rotate = keyframes`
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
`;


const StyledRotate = styled.div`
  display: inline-block;
  animation: ${rotate} 2s linear infinite;
  padding: 2rem 1rem;
  font-size: 1.2rem;
`;

export function App() {
  return (
    <StyledRotate>&lt;
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

王柳

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表