作者:mc_yang | 来源:互联网 | 2023-10-13 01:23
我试图在Angular2应用程序中使用元素调整大小检测器库(https:github.comwnrelement-resize-detector).根据我有限的JS模块知识,该库似
我试图在Angular2应用程序中使用元素调整大小检测器库(https://github.com/wnr/element-resize-detector).
根据我有限的JS模块知识,该库似乎采用CommonJS格式.经过多次尝试,我创建了以下定义文件(* .d.ts):
declare module ResizeDetector {
function ResizeDetector(options: any): ResizeDetector.Erd;
interface Erd {
listenTo(element: any, resizeCallback: any): void;
uninstall(element: any): void;
}
}
export = ResizeDetector;
然后我在我的TypeScript代码中使用以下import语句:
import * as ResizeDetector from 'element-resize-detector';
运行我的应用程序并使用console.log(‘ResizeDetector’,ResizeDetector)时,将记录以下输出:
ResizeDetector function (options) {
optiOns= options || {};
//idHandler is currently not an option to the listenTo function, so it should not be added to globalOptions.
var idHandler;
if (options.…
这告诉我库已成功加载并且它按预期返回一个函数.
我的问题是我现在如何开始在TypeScript中使用库?当我尝试这样的事情:
private static resizeDetector = ResizeDetector({ strategy: 'scroll' });
我得到以下转换错误:
error TS2349: Cannot invoke an expression whose type lacks a call signature.
解决方法:
元件调整大小-detector.d.ts
declare function elementResizeDetectorMaker(options?: elementResizeDetectorMaker.ErdmOptions): elementResizeDetectorMaker.Erd;
declare namespace elementResizeDetectorMaker {
interface ErdmOptions {
strategy?: 'scroll' | 'object';
}
interface Erd {
listenTo(element: HTMLElement, callback: (elem: HTMLElement) => void);
removeListener(element: HTMLElement, callback: (elem: HTMLElement) => void);
removeAllListeners(element: HTMLElement);
uninstall(element: HTMLElement);
}
}
export = elementResizeDetectorMaker;
消费者
let resizeDetector = elementResizeDetectorMaker({ strategy: 'scroll'});
resizeDetector.listenTo(document.getElementById('abc'), (elem: HTMLElement) => {
console.log(elem.offsetWidth, elem.offsetHeight);
})