【问题标题】:Don't unmount child if parent unmounts如果父级卸载,不要卸载子级
【发布时间】:2018-10-01 04:28:18
【问题描述】:

我有一个想要在新浏览器窗口中呈现的组件,我大致使用了这种技术:https://hackernoon.com/using-a-react-16-portal-to-do-something-cool-2a2d627b0202

这是它的简短摘录:

class MyWindowPortal extends React.PureComponent {
  constructor(props) {
    super(props);
    // STEP 1: create a container <div>
    this.containerEl = document.createElement('div');
    this.externalWindow = null;
  }
  
  render() {
    // STEP 2: append props.children to the container <div> that isn't mounted anywhere yet
    return ReactDOM.createPortal(this.props.children, this.containerEl);
  }

  componentDidMount() {
    // STEP 3: open a new browser window and store a reference to it
    this.externalWindow = window.open('', '', 'width=600,height=400,left=200,top=200');

    // STEP 4: append the container <div> (that has props.children appended to it) to the body of the new window
    this.externalWindow.document.body.appendChild(this.containerEl);
  }

  componentWillUnmount() {
    // STEP 5: This will fire when this.state.showWindowPortal in the parent component becomes false
    // So we tidy up by closing the window
    this.externalWindow.close();
  }
}

TL;DR:将反应门户附加到新窗口。

上述示例的完整工作代码笔:https://codepen.io/davidgilbertson/pen/xPVMqp

这就像一个魅力,甚至更新新窗口中的组件。由于门户是打开新窗口的组件的子组件,因此当我关闭父组件的页面(即一般卸载)时它也会关闭。

是否有可能保持新窗口打开并保留其中的当前内容?它不再需要更改,基本上将其冻结就可以了(没有状态更新等等)。只保留渲染的内容。

非常感谢任何帮助:)

【问题讨论】:

  • 您可以更改 Codepen 示例中的 &lt;App /&gt; 吗?
  • 我可以完全控制所有组件,如果这就是您的要求。不过,尽可能接近直接涉及的两个组件的解决方案会很好,而不需要一直到 root。

标签: javascript reactjs window.open portal unmount


【解决方案1】:

您只是不需要在关闭选项卡时调用closeWindowPortal()。 在 Codepen 示例中,您可以将其从 &lt;App /&gt; 中删除:

window.addEventListener('beforeunload', () => {
  this.closeWindowPortal();
});

【讨论】:

  • 那是codepen的明显解决方案,确实如此。在发布代码以说明我想要的内容时,我没有想到那个。问题是,我自己的 中没有这样的方法。看来我必须主动冻结这东西或其他东西。我正在使用 react-router,顺便说一句,如果有帮助的话。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-15
  • 2017-01-26
  • 2022-01-03
  • 2011-03-30
  • 2018-04-29
  • 1970-01-01
  • 2014-09-08
相关资源
最近更新 更多