javascript - 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
任何知道的解决方法?
解决方案
您可以尝试包装孩子:
return ReactDOM.createPortal(
<div id='portal'>{this.props.children}</div>, el);
根据需要设置样式,然后从子组件添加事件侦听器?
const portal = document.getElementById('portal');
portal.addEventListener(etc)
推荐阅读
- wpf - 当我应用此样式时,为什么我的功能区菜单按钮弹出窗口消失了?
- java - 无法注册客户端 - Spring Boot Admin 2.0.2
- jakarta-ee - 实体 JPA Hibernate 错误
- java - 用于从给定 DFA 打印所有接受的字符串(如果无限量则为上限)的算法
- python-3.x - 基于唯一 ID 和绘图图的 Pandas Dataframe 中两列的对角线差异
- javascript - 在 Laravel 中使用 AJAX 编辑字段
- ionic-framework - ios模拟器上的离子3导航问题
- javascript - 使用 chrome 扩展 javascript 将事件同步到谷歌日历
- c# - .NET Core,通过验证将字符串绑定到集合
- c - 分配 10kb 内存并打印地址和内容