gpt4 book ai didi

javascript - React 门户弹出窗口变量

转载 作者:行者123 更新时间:2023-12-04 13:57:31 25 4
gpt4 key购买 nike

我目前正在尝试使用 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可以包含将事件处理程序注册为的组件

image

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

https://codepen.io/ggcatu/pen/OJJGxYW?editors=0010
我想计算弹出 X & Y。
我不想通过 this.state.win到新的 child ,因为他们可以包含库组件,只是直接调用 window.screenX
任何知道的解决方法?

最佳答案

您可以尝试包装 child :

return ReactDOM.createPortal(
<div id='portal'>{this.props.children}</div>, el);
根据需要设置样式,然后从子组件添加事件监听器?
const portal = document.getElementById('portal');
portal.addEventListener(etc)

关于javascript - React 门户弹出窗口变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58997258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com