首页 > 解决方案 > 具有多个可能值的样式化组件道具

问题描述

我目前正在尝试动态构建一个 Typography 组件,我有两个主要的 propshtmlTag控件,用于标记组件将被渲染,以及一个typeprops 将控制它的样式。我有很多不同的类型,例如 h1、h2、body1、body2、标题、副标题...

我有一个工作代码,但它涉及大量代码重复,我怎样才能使它更清洁和可维护?使用函数switch case还是什么?我尝试了很多在stackoverflow上找到的方法,但没有成功

排版组件

import * as S from './styles'

export type Props = {
  children: React.ReactNode
  type: 'h1' | 'h2' | 'body1' | 'body2'
  htmlTag: 'h1' | 'h2' | 'p'
}

const Typography = ({ children, type, htmlTag }: Props) => (
  <S.Wrapper type={type} htmlTag={htmlTag}>
    {children}
  </S.Wrapper>
)

export default Typography

排版风格

import styled, { css, DefaultTheme } from 'styled-components'
import { Props } from '.'

type WrapperProps = Omit<Props, 'children'>

export const Wrapper = styled('h1').attrs<WrapperProps>(({ htmlTag }) => ({
  as: `${htmlTag}`
}))<WrapperProps>`
  ${({ theme }) => css`
    color: ${theme.colors.primary.primary01};
  `};
  ${({ type, theme }) =>
    type === 'h1' &&
    css`
      font-size: ${theme.font.sizes.xxxxlarge};
      font-weight: ${theme.font.weights.extraBold};
    `};
  ${({ type, theme }) =>
    type === 'h2' &&
    css`
      font-size: ${theme.font.sizes.xxxlarge};
      font-weight: ${theme.font.weights.bold};
    `};
  ${({ type, theme }) =>
    type === 'body1' &&
    css`
      font-size: ${theme.font.sizes.large};
      font-weight: ${theme.font.weights.normal};
    `};
  ${({ type, theme }) =>
    type === 'body2' &&
    css`
      font-size: ${theme.font.sizes.medium};
      font-weight: ${theme.font.weights.normal};
    `};
`

更新:

我已经能够将它用作开关盒,但不能将开关逻辑提取到一个函数中以解耦这些职责,关于如何实现这一点的任何建议?

export const Wrapper = styled('h1').attrs<WrapperProps>(({ htmlTag }) => ({
  as: `${htmlTag}`
}))<WrapperProps>`
  ${({ theme, type }) => css`
    color: ${theme.colors.primary.primary01};
    ${() => {
      switch (type) {
        case 'h1':
          return `font-size: ${theme.font.sizes.xxxxlarge}; font-weight: ${theme.font.weights.extraBold};`
        case 'h2':
          return `font-size: ${theme.font.sizes.xxxlarge}; font-weight: ${theme.font.weights.bold};`
      }
    }}
  `};
`

标签: javascriptcssreactjstypescriptstyled-components

解决方案


推荐阅读