【问题标题】:Type error while using antd Button with TypeScript使用带有 TypeScript 的 antd 按钮时出现类型错误
【发布时间】:2019-09-02 00:48:12
【问题描述】:

我像这样使用Button by antd@3.16.2

<Button
  type="primary"
  loading={true}
  onClick={console.log}
  block
>
  Do something
</Button>

这是我在尝试编译时看到的错误。

Error:(231, 26) TS2740: Type '{ children: string; type: "primary"; loading: boolean; onClick: () => void; block: true; }' is missing the following properties from type 'Pick<Pick<(Readonly<NativeButtonProps> & Readonly<{ children?: ReactNode; }>) | (Readonly<AnchorButtonProps> & Readonly<{ children?: ReactNode; }>), "children" | "style" | ... 257 more ... | "block"> & Pick<...> & Pick<...>, "children" | ... 256 more ... | "shape">': style, title, className, prefixCls, and 251 more.

这是什么意思,我应该在哪里解决这种类型不一致的问题?

【问题讨论】:

  • 只是出于好奇,如果你删除 onClick 处理程序,它还在对你大喊大叫吗?
  • 我正在使用这个 antd 并且看不到这个错误。但也许回调参数可能有问题?按钮 onClick 道具将传递参数 React.MouseEventHandler 或类似的东西。所以尝试用这个参数定义你的callbak。输入 myCallBacc: (event: React.MouseEventHandler) => void
  • 我刚刚去掉了回调函数,错误依然存在。

标签: reactjs typescript antd


【解决方案1】:

根据this question@types/react@16.8.11可以解决这个问题。

【讨论】:

    【解决方案2】:

    只需将您的 antd 更新到 3.16.3 或更高版本即可。

    执行:npm i antd@3.16.3 --saveyarn antd@3.16.3

    执行npm i antd@latest --save 获取最新信息。

    如果您想了解更多详情,可以在this issue找到

    【讨论】:

      【解决方案3】:

      您不能将 console.log 放在 onClick 方法中。 如果你愿意,你可以创建一些函数,该函数是控制台日志

      例如:

      handleClick = (event) => {
        console.log(event)
      }
      

      你可以这样调用函数:

      <Button
        type="primary"
        loading={true}
        onClick={this.handleClick}
        block
      >
        Do something
      </Button>
      

      【讨论】:

      • 我提到的错误不是关于我使用什么样的回调,因为我把console.log作为一个例子。实际上有我的功能。问题更多在于 TypeScript 定义不一致。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      相关资源
      最近更新 更多