我正在尝试为 react-grid-layout 提供*.d.ts
文件。正如其index.js文件显示它导出一个函数 - React.Component
的子类ReactGridLayout
:
// 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上描述的this declaration file on 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, ...
答案 0 :(得分:2)
因为react-grid-layout
正在导出ReactGridLayout
类&#34;直接&#34;而不是default
你不能做export default
(你已经看过已经发生的事情)。我认为你必须解决export =
语法,但这似乎限制你只导出一件事。解决此问题的一种方法是使用TypeScript的声明合并。导出具有相同名称的类和命名空间。它或多或少是react-grid-layout
正在做的事情。
<强> main.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>
<强> types.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;
}
BTW:您可能会发现更容易查看react-grid-layout
的ES6代码。