问题描述
我正在使用 react-new-window
在新窗口中加载一个小组件。在那里,它使用 html2canvas
导出为 png。我希望从新打开的窗口调用导出函数,以便可以导出其元素,而不是父窗口中的元素。
问题:总是从父窗口调用导出函数takeScreenShot()
,html2canvas
在新的子窗口中找不到元素,因为它正在查询父窗口。
/*Export is the parent,functional component,which creates a pop up menu so user can copy item to clipboard,or export to a file as a screenshot*/
const Export = (props) => {
/*redacted*/
const [showWindowPortal,toggleWindowPortal] = useState(false); /*toggles new window with specific item */
const takeScreenShot = () => {
let id = `#${card.tag}`;
html2canvas(document.querySelector(id),{}).then((canvas) => {
/*redacted*/
});
});
};
return(
/*redacted*/
{showWindowPortal && (
<NewWindow
onUnload={() => {
toggleWindowPortal(false); //turns off toggle on close
}}
onopen={() => console.log('opened')} //this property's function is called in the parent
features={features}
>
<div id={card.tag}>
<Card/>
</div>
</NewWindow>
)}
我尝试从以下位置调用 takeScreenShot()
:
- 子窗口中按钮的
onClick
属性 -
onopen
中的<NewWindow/>
道具 - 来自以
[useEffect]
或NewWindow
作为参数的showWindowPortal
钩子(这不应该起作用,我知道)
到目前为止没有任何效果,函数内的 document.querySelector
始终在父函数内。
有什么想法吗?谢谢!
解决方法
我找到了解决方案。我需要引用新的子窗口,并在 html2canvas 中访问该引用的文档。
我添加了 name="exportPopup"
作为 <NewWindow/>
的道具。
var newWindow = window.open('','exportPopup'); //Reference the popup
const takeScreenShot = () => {
let id = `#${card.tag}`;
console.log(id);
//use the reference for html2canvas
html2canvas(newWindow.document.querySelector(id),{}).then((canvas) => {
canvas.toBlob((blob) => {
var file = new File([blob],'test.png',{
type: 'application/octet-stream',});
document.location.href = URL.createObjectURL(file);
});
});
};