我称我为查看器对象,该对象将某些东西装入ID为tgmlviewer
的元素中。当我只有一个这样的组件时,这可以很好地工作。
import React, { useEffect } from "react";
import { Viewer } from "../../tgmlViewer/Viewer";
import { disableTgmlPointerEvents } from "../../../constants";
import { XmlType } from "./XmlView";
type Props = {
serialized: string;
xmlType: XmlType;
};
const tgmlViewerId = "tgmlviewer";
export default function TgmlImageViewer(props: Props) {
const { serialized, xmlType } = props;
useEffect(() => {
let viewer: Viewer;
const viewerElement = document.getElementById(tgmlViewerId);
if (viewerElement instanceof HTMLDivElement) {
viewer = new Viewer(viewerElement);
viewer.load(serialized);
}
return () => {
if (viewer) {
viewer.reset();
}
};
});
return (
<div
id={tgmlViewerId}
/>
);
}
现在,我想创建多个组件。每个组件都需要向其查看器对象传递唯一的ID。可以使用useRef
吗?
这是我的最佳尝试:
import React, { useEffect, useRef, Ref } from "react";
import { Viewer } from "../../tgmlViewer/Viewer";
import { disableTgmlPointerEvents } from "../../../constants";
import { XmlType } from "./XmlView";
type Props = {
serialized: string;
xmlType: XmlType;
};
export default function TgmlImageViewer(props: Props) {
const { serialized, xmlType } = props;
const tgmlViewerMountingTarget = useRef(null);
useEffect(() => {
if (!tgmlViewerMountingTarget) {
return;
}
let viewer: Viewer;
const viewerElement = tgmlViewerMountingTarget.current;
if (viewerElement instanceof HTMLDivElement) {
viewer = new Viewer(viewerElement);
viewer.load(serialized);
}
return () => {
if (viewer) {
viewer.reset();
}
};
});
return (
<div
ref={tgmlViewerMountingTarget}
/>
);
}
TypeScript错误
ts:const viewerElement:null //“ instanceof”表达式的左侧必须为“ any”类型,对象类型或类型参数。
答案 0 :(得分:0)
更改
const tgmlViewerMountingTarget = useRef(null);
到
const tgmlViewerMountingTarget = useRef<HTMLDivElement>(null);