【问题标题】:Prop TypeScript Error With React Component, Using Styled-ComponentsReact 组件的 Prop TypeScript 错误,使用 Styled-Components
【发布时间】:2021-11-25 02:29:48
【问题描述】:

我正在创建一个链接组件,它可以使用disabled 属性将颜色更改为灰色。当我将鼠标悬停在 {({ disabled } 上时,TypeScript 给了我一个 Property 'disabled' does not exist on type 'Pick<DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement> 错误。

语法看起来正确,不知道我在这里缺少什么。

const StyledLink = styled.a`

  color: blue;

  ${({ disabled }) => 
    disabled &&
    css`
      color: gray;
    `}
`;


export type TextLinkProps = {
  /**
   * text to be passed in as a link
   */
  link: string;
  /**
   * text to be rendered in the component.
   */
  children: React.ReactNode;
  /**
   * If `true`, color will be gray.
   */
  disabled?: boolean;
};

export function TextLink({ children, link, disabled = false }: TextLinkProps) {
  return (
    <StyledLink href={link} disabled={disabled}> 
      {children}
    </StyledLink>
  );
}

【问题讨论】:

    标签: reactjs typescript variables styled-components


    【解决方案1】:

    您应该指定您在样式化组件中获得的道具类型,如下所示:

    const StyledLink = styled.a<{ disabled?: boolean }>``
    

    也刚刚注意到,您可以简化样式以省略 css

    ${({ disabled }) => disabled && "color: gray"};
    

    【讨论】:

      【解决方案2】:

      TypeScript 是对的:锚元素没有属性 disabled

      https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

      【讨论】:

      • 他仍然可能希望将其用作基于给定条件的样式的自定义道具
      猜你喜欢
      • 2018-03-06
      • 2021-02-19
      • 2021-05-19
      • 1970-01-01
      • 2020-11-03
      • 2021-06-09
      • 2018-02-01
      • 2022-07-29
      • 2022-01-26
      相关资源
      最近更新 更多