You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在styled-components多个样式变量间共享基于props的条件样式?

Typography组件公共条件样式复用实现

你可以把所有依赖props触发的公共条件样式统一抽为可接收组件props的css片段,所有相关styled组件直接引入该片段即可,无需重复编写条件判断逻辑,也不会干扰各组件自身的独立样式配置。

重构后完整代码

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

// 统一定义所有组件共享的基础样式
const StyledTypographyBase = css`
  color: white;
  margin: 0;
  padding: 0;
`;

// 统一定义所有公共props对应的条件样式,所有公共触发逻辑统一在这里维护
const StyledTypographyCommonProps = css<{
  italic?: boolean;
  gutterBottom?: boolean;
}>`
  ${({ italic }) => italic && css`
    font-style: italic;
  `}
  ${({ gutterBottom }) => gutterBottom && css`
    margin-bottom: 0.5rem;
  `}
`;

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

// 所有标题组件直接引入公共片段即可,无需重复写italic等props的判断
export const h1 = styled('h1')`
  ${StyledTypographyBase};
  ${StyledHeader};
  ${StyledTypographyCommonProps};
  /* h1专属样式写在这里 */
  font-size: 2.5rem;
  font-weight: 700;
`;

export const h2 = styled('h2')`
  ${StyledTypographyBase};
  ${StyledHeader};
  ${StyledTypographyCommonProps};
  /* h2专属样式写在这里 */
  font-size: 2rem;
  font-weight: 600;
`;

export const h3 = styled('h3')`
  ${StyledTypographyBase};
  ${StyledHeader};
  ${StyledTypographyCommonProps};
  /* h3专属样式写在这里 */
  font-size: 1.5rem;
  font-weight: 600;
`;

export const h4 = styled('h4')`
  ${StyledTypographyBase};
  ${StyledHeader};
  ${StyledTypographyCommonProps};
  /* h4专属样式写在这里 */
  font-size: 1.25rem;
  font-weight: 500;
`;

export const Body = styled('p')<{ variant: 'body1' | 'body2' }>`
  ${StyledTypographyBase};
  ${StyledTypographyCommonProps};
  /* Body自身独立样式 */
  font-size: 16px;
  line-height: 1.5;

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

export const Caption = styled('p')`
  ${StyledTypographyBase};
  ${StyledTypographyCommonProps};
  /* Caption自身独立样式 */
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 0.05em;
`;

关键说明

  • 所有公共props(italic/gutterBottom等)的条件判断逻辑只需要在StyledTypographyCommonProps里维护一次,后续新增公共条件样式也只需要修改这一处
  • 每个组件的独立样式(比如h1-h4的字号、Body的variant逻辑、Caption的大写样式)完全和公共逻辑隔离,互不影响
  • 所有组件自动继承公共props的TS类型定义,不需要在每个styled组件声明处重复写<{ italic?: boolean }>这类泛型,TS会自动推导
  • 如果后续需要新增类似noWrap、align这类公共props,只需要在StyledTypographyCommonProps里追加对应的条件样式即可,所有组件会自动支持该属性
  • 如果部分组件不需要某类公共样式,不引入对应的公共css片段即可,灵活度完全可控

内容的提问来源于stack exchange,提问作者kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 20:03:24