阻止 React 显示用于样式化组件的道具?

Prevent React from displaying props meant for Styled-components?

我使用 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>

我希望 fontSizedisabled 成为仅针对 Styled-Components 的道具。我不希望他们申请 React 元素。 有没有更好的方法来做到这一点而不将道具名称更改为 styledFontSizestyledDisabled?

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

使用$瞬态道具:

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>
  )
}