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

样式系统中的标题组件

如何解决样式系统中的标题组件

如何使用样式系统和样式组件创建通用标题组件?

以下有效,但我所有的标题都使用 h1 标签

import css from "@styled-system/css"
import styled from "styled-components"
import { color,ColorProps,textAlign,TextAlignProps,variant } from "styled-system"

type Props = {
  level: 1 | 2 | 3 | 4 | 5 | 6
} & TextAlignProps &
  ColorProps

const Css = css({
  fontFamily: "heading",fontWeight: "heading",})

const Variant = variant({
  prop: "level",variants: {
    1: {
      fontSize: 7,lineHeight: 7,},2: {
      fontSize: 6,lineHeight: 6,3: {
      fontSize: 5,lineHeight: 5,4: {
      fontSize: 4,lineHeight: 4,5: {
      fontSize: 3,lineHeight: 3,6: {
      fontSize: 2,lineHeight: 2,})

const heading = styled("h1")<Props>(Css,Variant,color)

export default heading

我尝试创建一个 headingBase 组件,例如:

type Props = {
  level: 1 | 2 | 3 | 4 | 5 | 6,as: string | undefined
} & TextAlignProps &
  ColorProps

const headingBase = ({ level,as: Component = `h${level}`,...props }: Props) => <Component {...props} />

const heading = styled(headingBase)<Props>(Css,color)

但我在 <Component {...props} /> 处收到错误消息,因为它没有用于 TextAlignProps 和 ColorProps 的 API。

解决方法

也许您可以利用 as 以便在提供变体时,as 键会自动更改为变体字符串。这个用代码可能更容易解释,看一看。

const headingVariant = ({ fontSize }) => {
  let variantConfig = {
    h1: {
      fontSize: [7,8],//28px 32px
    },h2: {
      fontSize: [6,7],//24px 28px
    },h3: {
      fontSize: ['22px',6],//22px 24px
    },h4: {
      fontSize: 5,//20px
    },h5: {
      fontSize: 4,//18px
    },};

  if (fontSize) {
    variantConfig = Object.keys(variantConfig).reduce((acc,currKey) => {
      acc[currKey] = {
        ...variantConfig[currKey],fontSize,};
      return acc;
    },{});
  }
  return variant({
    prop: 'variant',variants: variantConfig,});
};

const Heading = styled(BaseText).attrs(
  ({ variant: hybridVariant,as: asOverride }) => ({
    as: asOverride ?? hybridVariant,})
)(
  ({ isBold,color }) =>
    css({
      fontFamily: `sofia-pro,Helvetica,Arial`,lineHeight: '130%',color: color || 'text',fontWeight: isBold ? 1 : 0,fontStyle: 'normal',}),headingVariant
);

Heading.propTypes = {
  isBold: PropTypes.bool,variant: PropTypes.string,};

Heading.defaultProps = {
  isBold: true,variant: 'h2',};

export default Heading;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。