首页 > 解决方案 > 防止 React 显示用于样式化组件的道具?

问题描述

Styled-ComponentsReact.

我的代码如下所示:

const StyledLink = styled.a<StyledProps>`
  font-size: ${(props) => pxToRem(props.fontSize!)};

  //disabled state
  ${(props) =>
    props.disabled &&
    css`
      color: grey;
      pointer-events: none;
    `}
`
const Link = ({href, disabled, fontSize = 16, children}: Props) => {
  return(
    <StyledLink href={href} fontSize={fontSize} disabled={disabled}>{children}</StyledLink>
  )
}

一切正常,但是当我检查我的元素时,我看到:

<a href="#" font-size="16" disabled>Some Link</a>

我想要fontSize并且disabled成为仅针对目标的道具Styled-Components。我不希望他们申请React元素。有没有更好的方法来做到这一点,而无需将道具名称更改为类似styledFontSizeand styledDisabled

标签: reactjstypescriptstyled-components

解决方案


styled-componentstransient props为那些想要避免属性传递到属性名称应该具有$(美元符号)前缀的 DOM 或 React 节点的人提供。

使用$瞬态道具

const StyledLink = styled.a<StyledProps>`
  font-size: ${(props) => pxToRem(props.$fontSize!)};

  //disabled state
  ${(props) =>
    props.$disabled &&
    css`
      color: grey;
      pointer-events: none;
    `}
`

const Link = ({href, disabled, fontSize = 16, children}: Props) => {
  return(
    <StyledLink href={href} $fontSize={fontSize} $disabled={disabled}>{children}</StyledLink>
  )
}


推荐阅读