首页 > 解决方案 > 无法将解构的道具分配给 react-bootstrap 组件

问题描述

我已经安装了react-bootstrap并想为我的项目自定义默认按钮,这样我就可以简单地编写大多数按钮<Button>而无需任何variant选项。

import * as bs from "react-bootstrap";

export const Button: bs.Button = ({
  variant = "outline-secondary",
  ...props
}) => {
  return <bs.Button variant={variant} {...props} />;
};

这会导致以下错误。

/path/to/MyComponent.tsx(11,11) 中的 TypeScript 错误:
Type '{ variant: string; } & Pick<PropsWithChildren<ReplaceProps<As, BsPrefixProps & ButtonProps>>, "slot" | ... 262 更多... | Exclude<...>>' 不可分配给类型 'IntrinsicAttributes & Pick<ComponentPropsWithRef, Exclude<keyof ComponentPropsWithRef, "slot" | ... 262 更多... | "onTransitionEndCapture">> & BsPrefixProps<...> & ButtonProps & { ...; }'。
输入'{变体:字符串;} & Pick<PropsWithChildren<ReplaceProps<As, BsPrefixProps & ButtonProps>>, "slot" | ... 262 更多... | Exclude<...>>' 不能分配给类型 'Pick<ComponentPropsWithRef, Exclude<keyof ComponentPropsWithRef, "

如果我在不解构的情况下编写它,它的工作原理就很简单。

export const Button: bs.Button = (props) => {
  return (
    <bs.Button {...props} variant={props.variant || "outline-secondary"} />
  );
};

为什么第一个不起作用?什么从props?

更新
版本:TypeScript 4.0.2、React 16.13.1、React Bootstrap 1.3.0

标签: reactjstypescriptreact-bootstrap

解决方案


你快到了。

您的代码不起作用,因为您没有声明道具的类型,所以您只需要这样做:

const ButtonX: bs.Button = ({
  variant = "outline-secondary",
  ...props
// Here´s the secret - a set props as bootstrap ButtonProps type
}: bs.ButtonProps) => {
  return <bs.Button variant={variant} {...props} />;
};

推荐阅读