微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决基于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 举报,一经查实,本站将立刻删除。