【问题标题】:calling a function from a new, child, window in react instead of parent window从新的子窗口调用函数而不是父窗口
【发布时间】:2021-05-08 13:58:53
【问题描述】:

我正在使用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():

  1. 子窗口中按钮的onClick 属性
  2. &lt;NewWindow/&gt; 中的 onOpen 属性
  3. 来自带有NewWindow 或showWindowPortal 作为参数的[useEffect] 钩子(我知道这应该不起作用)

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

有什么想法吗?谢谢!

【问题讨论】:

    标签: reactjs react-portal


    【解决方案1】:

    我找到了解决方案。我需要引用新的子窗口,并在 html2canvas 中访问该引用的文档。

    我将name="exportPopup" 作为道具添加到&lt;NewWindow/&gt;。

    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);
          });
        });
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多