1

我正在尝试为react-grid-layout*.d.ts提供一个文件。正如它的index.js文件所示,它导出了一个函数——被调用的子类:React.ComponentReactGridLayout

// react-grid-layout/index.js
module.exports = require('./build/ReactGridLayout').default;
module.exports.utils = require('./build/utils');
// ...

要求:

var ReactGridLayout = require('react-grid-layout');
console.log(ReactGridLayout);
// --> function ReactGridLayout(props , context) { ...

它还导出了一些其他东西,这些东西被分成了命名空间:

for (var f in ReactGridLayout) {
  if (ReactGridLayout.hasOwnProperty(f)) {
    console.log(f);
  }
}
// --> utils
// ...

所以它会进行一次导出多次导出。

我尝试了Typescript 站点上描述的Single Complex Object in Modules方法和GitHub 上的这个声明文件,但没有取得多大成功。

更新

现在忽略其他东西,我的定义ReactGridLayout如下:

// react-grid-layout.d.ts
declare module 'react-grid-layout' {

  import * as React from 'react';

  export default class ReactGridLayout<P,S> extends React.Component<P,S> {

    containerHeight():void;

    onWidthChange(width:number):void;

   /* more methods here ... */

}

哪个编译。但是它会生成如下 Javascript:

var react_grid_layout_1 = require('react-grid-layout');

React.createElement(react_grid_layout_1.default, null, ...

什么时候应该:

React.createElement(react_grid_layout_1, null, ...    
4

1 回答 1

2

因为这是“直接”react-grid-layout导出类而不是你不能做的(你已经看到了已经发生的事情)。我认为您必须解决语法问题,但这似乎将您限制为仅导出一件事。解决这个问题的一种方法是利用 TypeScript 的声明合并。导出同名的类和命名空间。它或多或少是在做什么。ReactGridLayoutdefaultexport defaultexport =react-grid-layout

主要的.tsx

import * as React from 'react'
import * as ReactGridLayout from 'react-grid-layout'

var grid = new ReactGridLayout(null, null);
var responsiveGrid = new ReactGridLayout.ResponsiveReactGridLayout(null, null);

<ReactGridLayout></ReactGridLayout>
//<ReactGridLayout.ResponsiveReactGridLayout></ReactGridLayout.ResponsiveReactGridLayout>

main.js(转译)

"use strict";
var React = require('react');
var ReactGridLayout = require('react-grid-layout');
var grid = new ReactGridLayout(null, null);
var responsiveGrid = new ReactGridLayout.ResponsiveReactGridLayout(null, null);
React.createElement(ReactGridLayout, null);
//<ReactGridLayout.ResponsiveReactGridLayout></ReactGridLayout.ResponsiveReactGridLayout>

类型.d.ts

declare module 'react-grid-layout' {

    import * as React from 'react';

    class ReactGridLayout extends React.Component<ReactGridLayout.Props, ReactGridLayout.State> {
        // members
    }

    namespace ReactGridLayout {
        export interface State {
            activeDrag?: any; // declare LayoutItem, etc..
            // etc...
        }

        export interface Props {
            className?: string
            // etc...
        }

        export class ResponsiveReactGridLayout extends React.Component<any, any>
        {
            // etc
        }
    }

    export = ReactGridLayout;
}

顺便说一句:您可能会发现查看react-grid-layout.

于 2016-06-28T16:10:47.843 回答