0

我正在使用react-new-window在新窗口中加载一个小组件。在那里,它被分阶段导出为使用html2canvas. 我希望从新打开的窗口调用导出函数,以便可以导出其元素,而不是父窗口中的元素。

问题:导出函数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()

  1. 子窗口中的按钮onClick道具
  2. onOpen道具_<NewWindow/>
  3. 从带有或作为参数的[useEffect]钩子(我知道这不应该起作用)NewWindowshowWindowPortal

到目前为止,没有任何效果,并且document.querySelector函数内部始终位于父函数内部。

有什么想法吗?谢谢!

4

1 回答 1

0

我找到了解决方案。我需要引用新的子窗口,并在 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);
      });
    });
  };
于 2021-05-10T13:51:46.283 回答