我设计了下面的按钮使用TailwindCSS与onClick事件.

<button className="border bg-purple-600 rounded-lg text-white px-2 py-1 mb-4" onClick={handleClick}>
  Add Item
</button>

现在,我try 为该按钮创建一个Reaction组件.我想在任何地方使用这个组件,有时它会有onClickprops ,有时onMouseDown等等.所以我试图在组件内的按钮元素上设置传递给我的组件的任何props .我想出了以下几点.

function Button({
  children,
  ...props
}: {
  children: React.ReactNode;
  props?: any;
}) {
  return (
    <button
      className="border bg-purple-600 rounded-lg text-white px-2 py-1 mb-4"
      {...props}
    >
      {children}
    </button>
  );
}

我不知道要设置什么类型的props ,所以我暂时将其设置为any.此代码不显示任何错误.

但当我try 使用下面的组件时,它显示: Type '{ children: string; onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & { children: ReactNode; props?: any; }'

<Button onClick={handleClick}>
   Add Item
</Button>

我怎么才能让它正常工作呢?

推荐答案

{
  children: React.ReactNode;
  props?: any; // 👈 this is incorrect
}

您的组件不接受props属性.取而代之的是,你在传播其余的props .这意味着上面的类型定义与您传递给它的内容不匹配.

假设您正在创建一个按钮包装器,您可以使用它的默认属性(已经包括children个属性).

import type { ButtonHTMLAttributes } from "react";

function Button({
  children,
  ...props
}: ButtonHTMLAttributes<HTMLButtonElement>) {
  // ...
}

您可能还希望防止消费者传入className,这会覆盖您自己的类.

你可以在后面加上你的.

<button
  {...props}
  className="border bg-purple-600 rounded-lg text-white px-2 py-1 mb-4"
>
  {children}
</button>

或在props 类型中明确禁止

type ButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className">;

function Button({
  children,
  ...props
}: ButtonProps) {
  return (
    <button
      className="border bg-purple-600 rounded-lg text-white px-2 py-1 mb-4"
      {...props}
    >
      {children}
    </button>
  );
}

Typescript相关问答推荐

无法将select选项的值设置为ngFor循环中的第一个元素

使Typescribe强制所有对象具有相同的 struct ,从两个选项

当方法参数和返回类型不相互扩展时如何从类型脚本中的子类推断类型

类型脚本中没有接口的中间静态类

是否使用非显式名称隔离在对象属性上声明的接口的内部类型?

使用TypeScrip根据(可选)属性推断结果类型

APIslice-CreateAPI的RTK打字错误

如何将所有props传递给React中的组件?

Angular 17子路由

为什么ESLint会抱怨函数调用返回的隐式`any`?

从对象类型描述生成类型

为什么Typescript只在调用方提供显式泛型类型参数时推断此函数的返回类型?

将带有样式的Reaction组件导入到Pages文件夹时不起作用

类型脚本-处理值或返回值的函数

为什么特定的字符串不符合包括该字符串的枚举?

如何在不违反挂钩规则的情况下动态更改显示内容(带有状态)?

如何通过转换器类继承使用多态将对象从一种类型转换为另一种类型

使用&reaction测试库&如何使用提供程序包装我的所有测试组件

Vite+Chrome扩展 list v3-;不能在模块外使用import语句;对于inpage脚本

元组解释