基于Chakra-UI组件创建具有变体的React组件

问题描述

我正在尝试使用chakra-ui https://chakra-ui.com/中的headingText组件来创建一些排版组件。想法是这些组件在其中包含我想要的所有行高,字母间距,字体粗细和其他样式。

例如,一个<displayOne>组件的font-size为96px,一个line-height的100%,等等。一个<displayThree>组件具有一个font-weightline-height为72px。等等。

现在,这可行,但是它并不像我想要的那样优雅。理想情况下,我想要这样的东西:

<heading level="d1">display One</heading>
<heading level="d2">display Two</heading>
<heading level="d3">display Three</display>
...
<Text level="small">Small Text</Text>
...

换句话说,不是具有多个组件,而是具有一个带有控制变化的道具的组件。不过,我遇到了麻烦,想出如何使它正常工作。

现在,这就是我的代码

import { heading,Text } from '@chakra-ui/core'

const TextBase = ({ children,...rest }) => (
  <Text color="darkGrey" fontWeight="semibold" lineHeight="base">
    {children}
  </Text>
)

const headingBase = ({ children,...rest }) => (
  <heading color="dark" fontWeight="bold" letterSpacing="tight">
    {children}
  </heading>
)

// display
export const displayOne = ({ children,...rest }) => (
  <headingBase fontSize="96px" lineHeight="100%" {...rest}>
    {children}
  </headingBase>
)

export const displayTwo = ({ children,...rest }) => (
  <headingBase fontSize="88px" lineHeight="100%" {...rest}>
    {children}
  </headingBase>
)

...

// Text
export const BodyText = ({ children,...rest }) => (
  <TextBase fontSize="md" {...rest}>
    {children}
  </TextBase>
)

export const SmallText = ({ children,...rest }) => (
  <TextBase fontSize="sm" {...rest}>
    {children}
  </TextBase>
)
...

我想做的是这样的:

import { heading as headingBase,Text as TextBase } from '@chakra-ui/core'```

export const heading = (props) => {
  if (props.level === "d1") {
     return <heading fontSize="96px"...>{props.children}</heading>
} else if (props.level === "d2") { ... }
 ...
}
}

但是,这似乎很复杂,不是很枯燥,我想知道是否有一种更简单和/或更优雅的方式来做到这一点。

有什么想法吗?

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)