首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React-portal -使用浏览器关闭按钮关闭新窗口

React-portal -使用浏览器关闭按钮关闭新窗口
EN

Stack Overflow用户
提问于 2019-01-29 13:56:38
回答 2查看 1.2K关注 0票数 0

我在我的应用程序中实现了类似的东西:

https://codepen.io/gaearon/pen/mjGvRV?editors=0010

但是,当我单击新窗口中的浏览器关闭按钮时,"componentWillUnmount“不会被调用,这就是为什么即使我使用浏览器关闭按钮关闭门户网站,状态也不会改变。这个问题有什么解决方案吗?如何捕捉react门户的“浏览器关闭按钮”?

代码语言:javascript
复制
componentWillUnmount() {
    this.state.win.close();
  }
EN

回答 2

Stack Overflow用户

发布于 2019-01-29 13:59:59

我认为您应该这样做,使用componentDidMountcomponentWillUnmount来添加和删除侦听器。

代码语言:javascript
复制
  componentDidMount() {
    window.addEventListener('beforeunload', this.handleSomething.bind(this));
  }
  componentWillUnmount() {
    window.removeEventListener('beforeunload', this.handleSomething.bind(this));
  }
  handleSomething(event) {
       event.preventdefault();
       this.state.win.close();
  }
票数 0
EN

Stack Overflow用户

发布于 2019-01-29 17:00:05

在应用程序中将closeWindowPortal方法作为道具发送到窗口

代码语言:javascript
复制
<Window closeWindowPortal={() => this.closeWindowPortal()}>
    <CounterButton />
    <button onClick={() => this.closeWindowPortal()}>Close</button>
</Window>

然后用这个替换窗口组件

代码语言:javascript
复制
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);
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54414682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档