【问题标题】:Cannot assign destructured props to react-bootstrap component无法将解构的道具分配给 react-bootstrap 组件
【发布时间】:2020-08-22 07:53:49
【问题描述】:

我已经安装了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 错误:
输入'{变体:字符串; } & Pick>, "slot" | ... 262 更多... | Exclude<...>>' 不可分配给类型 'IntrinsicAttributes & Pick> & BsPrefixProps<...> & ButtonProps & { ...; }'。
输入'{变体:字符串; } & Pick>, "slot" | ... 262 更多... | Exclude<...>>' 不可分配给类型 'Pick>'。 TS2322

如果我在不解构的情况下编写它,那么它的工作原理就是这样。

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

【问题讨论】:

  • 当您以这种方式传播时,您的...props 将来自Pick&lt;PropsWithChildren&lt;ReplaceProps ...&gt; 其中PropsWithChildren... 是相当复杂的react-boostrap 计算。我认为它现在包含问题。因此,要破解这个,您只需指定道具的类型。然后它会工作bs.ButtonProps
  • @tmhao2005 你说得有道理。我通常不喜欢说某些东西不是我的错误而是工具的错误,但是,您的评论确实很有意义,因为 TS 从原始参数推断出一个复杂类型 React.PropsWithChildren&lt;ReplaceProps&lt;As, BsPrefixProps&lt;As&gt; &amp; bs.ButtonProps&gt;&gt; 而没有解构

标签: reactjs typescript react-bootstrap


【解决方案1】:

你快到了。

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

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

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2020-01-17
    • 2017-05-15
    • 1970-01-01
    • 2021-06-30
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多