我在我的应用程序中实现了类似的东西:
https://codepen.io/gaearon/pen/mjGvRV?editors=0010
但是,当我单击新窗口中的浏览器关闭按钮时,"componentWillUnmount“不会被调用,这就是为什么即使我使用浏览器关闭按钮关闭门户网站,状态也不会改变。这个问题有什么解决方案吗?如何捕捉react门户的“浏览器关闭按钮”?
componentWillUnmount() {
this.state.win.close();
}发布于 2019-01-29 13:59:59
我认为您应该这样做,使用componentDidMount和componentWillUnmount来添加和删除侦听器。
componentDidMount() {
window.addEventListener('beforeunload', this.handleSomething.bind(this));
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.handleSomething.bind(this));
}
handleSomething(event) {
event.preventdefault();
this.state.win.close();
}发布于 2019-01-29 17:00:05
在应用程序中将closeWindowPortal方法作为道具发送到窗口
<Window closeWindowPortal={() => this.closeWindowPortal()}>
<CounterButton />
<button onClick={() => this.closeWindowPortal()}>Close</button>
</Window>然后用这个替换窗口组件
class Window extends React.Component {
constructor(props) {
super(props);
this.state = { win: null, el: null };
this.hendleClose = this.hendleClose.bind(this);
}
componentDidMount() {
let win = window.open('', '', 'width=600,height=400');
win.document.title = 'A React portal window';
let el = document.createElement('div');
win.document.body.appendChild(el);
this.setState({ win, el });
win.onbeforeunload = this.hendleClose
}
hendleClose(){
this.props.closeWindowPortal()
}
componentWillUnmount() {
this.state.win.close();
}
render() {
const { el } = this.state;
if (!el) {
return null;
}
return ReactDOM.createPortal(this.props.children, el);
}
}https://stackoverflow.com/questions/54414682
复制相似问题