【问题标题】:Type '{}' has no properties in common with type 'IntrinsicAttributes'类型 \'{}\' 与类型 \'IntrinsicAttributes\' 没有共同的属性
【发布时间】:2023-01-05 21:25:42
【问题描述】:

我在 React TypeScript 中创建了一个动态按钮 (Comp)。 “Comp”可以是按钮、锚点或链接(React Router)。我遇到了一个关于类型没有与类型@​​987654321@ 共有的属性的问题。

type ButtonProps = {
  href?: string;
  to?: string;

  children: ReactNode;
};

function Button(props: ButtonProps) {
  const { href, to, solid, outline, children } = props;

  let Comp = 'button';
  if (href) Comp = 'a';
  if (to) Comp = 'Link';

  const compProps = { 
    href,
    to,
  };

  return <Comp {...compProps}>{children}</Comp>;
}

这是问题:

Type '{ children: ReactNode; href: string | undefined; to: string | undefined; }' has no properties in common with type 'IntrinsicAttributes'.ts(2559).

我在 StackOverflow 中研究了一些图片,但这不是我的情况。

【问题讨论】:

  • 您不能将字符串用作 JSX 构造函数,Comp 不是有效标记。

标签: reactjs typescript intrinsicattributes


【解决方案1】:

您不能将字符串用作 JSX 构造函数:Comp 不是有效标记。

您可以像这样重写代码:

type ButtonProps = {
  href?: string;
  to?: string;

  children: ReactNode;
};

function Button(props: ButtonProps) {
  const { href, to, children } = props;

  if (href) return <a href={href}>{children}</a>;
  if (to) return <Link to={to}>{children}</Link>;
  return <button>{children}</button>;
}

【讨论】:

    猜你喜欢
    • 2022-08-17
    • 2022-10-17
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2022-07-05
    相关资源
    最近更新 更多