【问题标题】:Prevent React from displaying props meant for Styled-components?防止 React 显示用于样式化组件的道具?
【发布时间】:2021-10-16 13:06:58
【问题描述】:

我使用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.com/docs/api#transient-props 其中美元符号前缀避免属性传递到 DOM
  • Mic Fung,这是一个很好的答案。如果你能把它留在下面,我可以把它标记为正确的。

标签: reactjs typescript styled-components


【解决方案1】:

styled-components 为那些希望避免属性向下传递到属性名称应具有 $(美元符号)前缀的 DOM 或 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>
  )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 2021-09-18
    • 2018-10-09
    • 2021-09-15
    • 2021-12-13
    • 2021-10-28
    • 2021-01-13
    • 2021-03-09
    相关资源
    最近更新 更多