对React组件的打字稿定义文件进行故障排除

时间:2018-07-30 09:39:51

标签: reactjs typescript

我目前正在使用React 16.4.1和Typescript 2.9.2。我正在尝试利用reaptcha库:

https://github.com/sarneeh/reaptcha

我这样导入的:

import * as Reaptcha from 'reaptcha';

由于没有提供类型定义,因此构建当前会给我这个(预期的)错误:

TS7016: Could not find a declaration file for module 'reaptcha'. '...' implicitly has an 'any' type.

尽管出现此错误,代码“仍然有效”,但是我已经尝试了很长时间来构建足以定义该错误的定义文件。根据库的导出方式,似乎有很多不同的方法可以完成此操作,但我似乎并没有找到合适的组合。对于此定义:

declare module "reaptcha" {
  import * as React from "react";
  export default class Reaptcha extends React.Component<any, any> {
  }
}

这并没有解决问题,而是提出了另一个错误。

TS2604: JSX element type 'Reaptcha' does not have any construct or call signatures.

这后一个错误,我很坚持。超过此限制的任何帮助。

使用该组件的最小情况是:

  public render() {
    const Fragment = React.Fragment;
    return (
      <Fragment>
        <Reaptcha
          ref={(e: any) => (this.captcha = e)}
          sitekey="MY KEY"
          onVerify={this.onVerify}
        />
      </Fragment>
    );
  }

2 个答案:

答案 0 :(得分:1)

您可以使用:

declare module "reaptcha";

答案 1 :(得分:1)

Reaptcha readme将导入显示为:

import Reaptcha from 'reaptcha';

我用您的原始声明尝试了这种导入样式,TypeScript很高兴,但是导入在运行时无法正常工作。当我启用--esModuleInterop TypeScript选项时,一切正常。如果尚未尝试使用此选项。

相关问题