繁体   English   中英

如何跨样式组件变量共享道具?

[英]how to share props across styled-component variables?

我正在创建一个Typography组件(类似于 mui 的实现),并试图弄清楚如何在所有实例中分配某些基于条件的 prop 样式。 -- 像斜体或 gutterBottom ...

import styled, { css } from 'styled-components';

const StyledTypography = css`
  color: white;
  margin: 0;
  padding: 0;
`;

const StyledHeader = css`
  margin-bottom: 1rem;
`;

export const h1 = styled('h1')<{ italic?: boolean }>`
  ${StyledTypography};
  ${StyledHeader};

  ${({ italic }) => italic && 'font-style: italic;'};
  // - I don't want to repeat the previous line in every variable
  // - I'd rather it be defined in one place and inherited while still respecting h1, h2, h3, etc.
`;
export const h2 = styled('h2')`
  ${StyledTypography};
  ${StyledHeader}
`;
export const h3 = styled('h3')`
  ${StyledTypography};
  ${StyledHeader}
`;
export const h4 = styled('h4')`
  ${StyledTypography};
  ${StyledHeader}
`;

export const Body = styled('p')<{ variant: 'body1' | 'body2' }>`
  ${StyledTypography};

  font-size 16px;

  ${({ variant }) =>
    variant === 'body2' &&
    css`
    font-size 14px;
  `}}
`;

export const Caption = styled('p')`
  ${StyledTypography};

  font-size 14px;
  text-transform: uppercase;
`;

想通了,对于任何在未来偶然发现的人......

import styled, { css } from 'styled-components';
import { ITypography } from '.';

type TypographyStyles = Omit<ITypography, 'variant' | 'children'>;

const StyledTypography = css<TypographyStyles>`
  color: white;
  margin: 0;
  padding: 0;

  ${({ italic }) => italic && 'font-style: italic;'};
`;

const StyledHeader = css`
  margin-bottom: 1rem;
`;

export const h1 = styled('h1')<TypographyStyles>`
  ${StyledTypography};
  ${StyledHeader};
`;
export const h2 = styled('h2')<TypographyStyles>`
  ${StyledTypography};
  ${StyledHeader}
`;
export const h3 = styled('h3')<TypographyStyles>`
  ${StyledTypography};
  ${StyledHeader}
`;
export const h4 = styled('h4')<TypographyStyles>`
  ${StyledTypography};
  ${StyledHeader}
`;

export const Body = styled('p')<TypographyStyles & { variant: 'body1' | 'body2' }>`
  ${StyledTypography};

  font-size 16px;

  ${({ variant }) =>
    variant === 'body2' &&
    css`
    font-size 14px;
  `}}
`;

export const Caption = styled('p')<TypographyStyles>`
  ${StyledTypography};

  font-size 14px;
  text-transform: uppercase;
`;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM