【问题标题】:Refactoring styled components [duplicate]重构样式化的组件
【发布时间】:2021-04-14 06:53:27
【问题描述】:

我正在使用样式化的组件,并且我有不同的元素/图标需要相同的样式。如果我有不同类型的“图标”但样式相同,有什么方法可以重构它?在我的样式化组件代码中最小化重复的正确语法是什么?

import React from 'react';
import styled from 'styled-components';
import FolderIcon from 'src/assets/images/folder.svg';
import ListIcon from 'src/assets/images/clipboard.svg';

const StyledIcon = styled.div`
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
`;

const StyledListIcon = styled(ListIcon)`
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
`;

const StyledFolderIcon = styled(FolderIcon)`
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
`;

const MenuItem = (props) => {
    const { label, nodeType, onClick, icon } = props;

    return (
        <MenuItem onClick={onClick}>
            {nodeType === 'LIST' ? (
                <StyledListIcon />
            ) : icon ? (
                <StyledIcon>{icon}</StyledIcon>
            ) : (
                <StyledFolderIcon />
            )}
            <span>{label}</span>
        </MenuItem>
    );
};

export default MenuItem;

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    这是css 块的用例:

    const iconStyle = css`
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
    `;
    
    const StyledIcon = styled.div`
      ${iconStyle}
    `;
    
    const StyledListIcon = styled(ListIcon)`
      ${iconStyle}
    `;
    
    const StyledFolderIcon = styled(FolderIcon)`
      ${iconStyle}
    `;
    

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 2020-08-19
      • 2020-09-26
      • 2020-09-22
      • 2020-02-01
      • 2021-07-02
      • 2020-10-19
      • 2021-01-12
      • 2018-11-15
      相关资源
      最近更新 更多