首页 > 解决方案 > React 门户弹出窗口变量

问题描述

我目前正在尝试使用ReactDOM.createPortal. 我已经浏览了https://github.com/facebook/react/issues/12355 并使用了以下代码

class Window extends React.Component {
  constructor(props) {
    super(props);
    this.state = { win: null, el: null };
  }

  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 });
  }

  componentWillUnmount() {
    this.state.win.close();
  }

  render() {
    const { el } = this.state;
    if (!el) {
      return null;
    }
    return ReactDOM.createPortal(this.props.children, el);
  }
}

主要问题是它this.props.children可以包含将事件处理程序注册为的组件

图片

windows变量仍然是指主窗口,而不是最近打开的弹出窗口。

https://codepen.io/ggcatu/pen/OJJGxYW?editors=0010 我想计算弹出 X 和 Y。我不想传递this.state.win给新的孩子,因为它们可以包含库组件,这只是直接调用window.screenX

任何知道的解决方法?

标签: javascriptreactjspopup

解决方案


您可以尝试包装孩子:

return ReactDOM.createPortal(
<div id='portal'>{this.props.children}</div>, el);

根据需要设置样式,然后从子组件添加事件侦听器?

const portal = document.getElementById('portal');
portal.addEventListener(etc)

推荐阅读