react-boostrap-typeahead的自定义Typescript定义

Custom Typescript Definition for react-boostrap-typeahead

本文关键字:定义 Typescript 自定义 react-boostrap-typeahead      更新时间:2023-09-26

我试图为react-bootstrap-typeahead创建一个自定义的Typescript定义。到目前为止,以下是我根据文档编写的内容:

// Custom made typings based on exampes: https://github.com/ericgio/react-bootstrap-typeahead
declare namespace ReactBootstrapTypeahead {
    import React = __React;
    // Input
    class ReactBootstrapTypeahead extends React.Component<ReactBootstrapTypeaheadProps, any> {
    }
    interface ReactBootstrapTypeaheadProps extends React.HTMLProps<ReactBootstrapTypeahead> {
        align?: string;
        allowNew?: boolean;
        defaultSelected?: any[];
        disabled?: boolean;
        emptyLabel?: string;
        labelKey?: string;
        maxHeight?: number;
        minLength?: number;
        multiple?: boolean;
        name?: string;
        newSelectionPrefix?: string;
        onBlur?(): any;
        onChange?(): any;
        onInputChange?(): any;
        options: any[];
        paginateResults?: number;
        paginationText?: string;
        placeholder?: string;
        renderMenuItemChildren?(): any;
    }
}
declare module 'react-bootstrap-typeahead' {
    export = ReactBootstrapTypeahead;
}

当我尝试使用组件时,我得到了几个错误:

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

对于Typescript的定义我还是个新手,如果有任何帮助,我将不胜感激。

当您为库编写声明文件时,强烈建议尝试将所有内容包装在模块化声明文件中,而不是全局声明文件中。

我首先拉入react (typings install react --save)的模块化声明文件。

然后我将修改您的声明文件,以专门从react中拉入类型。

custom-typings/react-bootstrap-typeahead

declare module 'react-bootstrap-typeahead' {
  import React = require('react')
  interface ReactBootstrapTypeaheadProps extends React.HTMLProps<ReactBootstrapTypeahead> {
    // ¯'_(ツ)_/¯
  }
  class ReactBootstrapTypeahead extends React.Component<ReactBootstrapTypeaheadProps, any> {
  }
  export = ReactBootstrapTypeahead
}

在项目的任何地方,这应该都可以正常编译

 import ReactTypeahead = require('react-bootstrap-typeahead')