javascript - 具有多个可能值的样式化组件道具
问题描述
我目前正在尝试动态构建一个 Typography 组件,我有两个主要的 propshtmlTag
控件,用于标记组件将被渲染,以及一个type
props 将控制它的样式。我有很多不同的类型,例如 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};`
}
}}
`};
`
解决方案
推荐阅读
- google-cloud-storage - 如何协调 Terraform 状态与现有存储桶?
- flutter - 使用颤振在本地保存值
- sql-server - 如何根据对命令提示符的响应使气流任务失败
- python - 为什么 date_range 给出的结果与 DataFrame Pandas 日期的索引 [] 不同?
- python - 如何有效地将 (start_time,[time_deltas]) 转换为 (start_time, end_time)?
- python - 熊猫的方式来增加出现次数
- angular - 删除 Angular 材料数据表 (Angular 7) 上循环行上的选定行
- javascript - jQuery Click Handler with Called Ajax Sub-Method 在 $(this).prop('disabled', true) 上有一个奇怪的延迟
- python - 缩放数据框中的字段
- c# - 如何使用“controller?action¶meters”路由实现 .NET WebAPI?