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

问题描述 投票:0回答:1

我使用 TailwindCSS 和 onClick 事件设计了下面的按钮。

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

现在我尝试为此按钮创建一个 React 组件。我想在任何地方使用这个组件,有时它会有 onClick 属性,有时会有 onMouseDown 等。所以我试图在组件内的按钮元素上设置传递给我的组件的任何属性。我想出了下面的。

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

我不知道如何设置道具类型,所以我暂时将其设置为

any
。这段代码没有显示任何错误。

但是当我尝试使用如下组件时,它说:

 Type '{ children: string; onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & { children: ReactNode; props?: any; }'

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

我怎样才能让它工作?

reactjs typescript react-props
1个回答
0
投票
{
  children: React.ReactNode;
  props?: any; // 👈 this is incorrect
}

您的组件不接受

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>

或者在prop类型中明确禁止

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>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.