我有一个要在新浏览器窗口中呈现的组件,我大致使用这种技术: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
这就像一个魅力,甚至更新新窗口中的组件。由于门户是打开新窗口的组件的子组件,因此当我关闭父组件的页面(即一般卸载)时,它也会关闭。
是否有可能保持新窗口打开并保留其中的当前内容?它不再需要更改,基本上将其冻结就可以了(没有状态更新等等)。只保留渲染的内容。
非常感谢任何帮助:)