【问题标题】:Open new tabs with portal react使用门户反应打开新标签
【发布时间】:2019-09-25 16:31:12
【问题描述】:

我正在尝试使用门户打开一个新选项卡,问题是该选项卡不显示我想要获得上一个的内容,我按照这个 post 并且选项卡完美打开,但不显示内容并查看像这样:

这是我的反应门户代码:

    import ReactDOM, {PureComponent} from 'react';

export default class Portal extends PureComponent{
  constructor(props) {
    super(props);
    this.containerEl = null;
    this.externalWindow = null;
  }

  componentDidMount() {
    this.externalWindow = window.open('', '', 'width=600,height=400,left=200,top=200');
    this.containerEl = this.externalWindow.document.createElement('div');
    this.externalWindow.document.body.appendChild(this.containerEl);
  }

  componentWillUnmount() {

    this.externalWindow.close();
  }

  render() {
    if (!this.containerEl) {
      return null;
    } 
    return ReactDOM.createPortal(this.props.children,this.containerEl);  
  }
}

这是我打开新标签的代码:

{this.state.showWindowPortal && (
            <Portal closeWindowPortal={this.closeWindowPortal} >
            <p>Hello</p>
       <button onClick={() => this.closeWindowPortal()} >Close me! 
  </button>
</Portal>)}

希望大家能帮帮我,谢谢!

【问题讨论】:

    标签: javascript reactjs window.open createelement react-portal


    【解决方案1】:

    您没有足够快地创建containerEl。 (它不需要在另一个窗口的文档中创建,我认为这就是你延迟它的原因。)要修复它,在构造函数中将 this.containerEl = null; 更改为 this.containerEl = document.createElement('div');,并从 @987654325 中删除 this.containerEl = this.externalWindow.document.createElement('div'); @。

    【讨论】:

      【解决方案2】:

      componentDidMountrender 之后执行。

      this.containerElcomponentDidMount 中设置为this.externalWindow.document.createElement('div');

      您在render 中检查this.containerEl,当时this.containerElnull

      有关 React 生命周期钩子顺序的更多信息,请查看http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 2023-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多