【问题标题】:How to remove duplication of code in styled components如何删除样式化组件中的重复代码
【发布时间】:2022-11-17 21:59:52
【问题描述】:

目前,我正在使用蚂蚁样式组件在我的项目中。

但是,在使用时蚂蚁作为一个组成部分样式组件,重复了以下代码。

import { DownOutlined, VerticalLeftOutlined } from '@ant-design/icons';
import styled from "styled-components";

const Button = styled(DownOutlined)`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;  
`;

const AnotherButton = styled(VerticalLeftOutlined)`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
`;

我想删除代码重复另一个按钮仅通过动态改变 () 部分的变量按钮多变的。

import { DownOutlined, VerticalLeftOutlined } from '@ant-design/icons';
import styled from "styled-components";

// How to dynamically apply DownOutlined, VerticalLeftOutlined inside ()
const Button = styled()`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;  
`;

有什么办法可以解决上面描述的问题吗?

【问题讨论】:

    标签: javascript css reactjs antd styled-components


    【解决方案1】:

    你可以移动常见的为变量添加样式,使其可在组件之间重用。

    import styled, { css } from "styled-components";
    
    const commonStyles = css`
      color: palevioletred;
      font-size: 1em;
      margin: 1em;  
    `;
    
    const Button = styled(DownOutlined)`
      ${commonStyles};
    `;
    
    const AnotherButton = styled(VerticalLeftOutlined)`
      ${commonStyles};
    `;
    

    【讨论】:

      猜你喜欢
      • 2021-08-03
      • 2013-03-26
      • 2019-02-28
      • 2021-09-11
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 2012-08-12
      • 2011-04-12
      相关资源
      最近更新 更多