gpt4 book ai didi

reactjs - 'ResizeObserver' 仅指一种类型,但在此处用作值

转载 作者:行者123 更新时间:2023-12-03 16:13:05 25 4
gpt4 key购买 nike

我收到错误:'ResizeObserver' only refers to a type, but is being used as a value here尝试在 React 中使用 ResizeObserver 和 TypeScript 时。

我将以下接口(interface)定义为 TypeScript 不包含定义:

interface ResizeObserver {
observe(target: Element): void;
unobserve(target: Element): void;
disconnect(): void;
}

我在以下组件中使用它:
const useWidth = () => {

const ref = useRef<HTMLObjectElement>(null);

const [width, setWidth] = useState(0);

useLayoutEffect(() => {

var resizeObserver = new ResizeObserver(() => console.log("blah blah blah"))
resizeObserver.observe(ref.current)

return () => resizeObserver.disconnect()

}, [ref.current])

return [ref, width];
}

最佳答案

您应该安装 @types/resize-observer-browser npm 包,to get the type declarations .如果你真的想自己动手,你可以通过 declare var 定义一个新的接口(interface)。在 *.d.ts文件。

declare interface ResizeObserver {
observe(target: Element): void;
unobserve(target: Element): void;
disconnect(): void;
}

declare var ResizeObserver: {
prototype: ResizeObserver;
new(callback: ResizeObserverCallback): ResizeObserver;
};

interface ResizeObserverSize {
inlineSize: number;
blockSize: number;
}

type ResizeObserverCallback = (entries: ReadonlyArray<ResizeObserverEntry>, observer: ResizeObserver) => void;

interface ResizeObserverEntry {
readonly target: Element;
readonly contentRect: DOMRectReadOnly;
readonly borderBoxSize: ResizeObserverSize;
readonly contentBoxSize: ResizeObserverSize;
}

然后它将在全局范围内可用(因为我相信它在浏览器中)并且您可以对其进行更新:

enter image description here

关于reactjs - 'ResizeObserver' 仅指一种类型,但在此处用作值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59683957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com