javascript - 反应中心 div
问题描述
我使用 react 来构建一个对话框组件,我希望能够计算 left 和 top 以使固定对话框位置居中。
我知道
left= windowWidth/2 -(dialogWidth /2)
问题是对话框宽度是动态生成的。
如何计算对话框宽度。
我不是在使用 css 之后我想使用 react 或 javascript 来获取这些数据。
这是我当前的组件
import * as React from 'react';
import { any } from 'prop-types';
export default class Dialog extends React.PureComponent<{
children: React.ReactDOM,
isOpen?: Boolean,
title?: string,
save?: Function
}>
{
public state = {
left: 0,
top: 0,
isOpen: this.props.isOpen
}
public toggle() {
/// Calculate position and toggld open
}
render() {
return (
<div className="dialog" style={{ left: this.state.left, top: this.state.top, display: (this.state.isOpen ?"block": "hidden") }}>
<h2 className="header">{this.props.title}
<span className="btn"></span>
</h2>
<div className="center"></div>
</div>
)
}
}
让我知道你的想法
解决方案
好的,使用 reactDOM 得到了解决方案
这里是如何
var el = ReactDom.findDOMNode(this) as HTMLElement;
var offset = el.getElementsByClassName("dialog")[0].getBoundingClientRect();
var left = window.outerWidth / 2 - (offset.width / 2);
var top = window.outerHeight / 2 - (offset.height / 2);
this.setState({ left: left, top: top });
推荐阅读
- javascript - 如何从开槽组件调用方法或向父组件发出事件?
- reactjs - ReactJS Eslint:误报缺少 JSDoc @return 类组件
- windows - 在 WebStorm 终端中使用 bash
- amazon-web-services - 从外部供应商 s3 存储桶到我(公司)的 AWS s3 存储桶的 SFTP
- php - 我正在尝试在查询结果中搜索字符串以查找某些数字
- unity3d - 在统一项目中导出 Blender 模型
- typescript - 使用 MyClass.defaults(options) 设置所需的构造函数选项时如何使它们成为可选
- java - 使用 Jackson 读取 Java 中的部分 yaml
- amazon-web-services - 有没有办法将 Kinesis Firehose 连接到 Lambda,然后连接到 S3?
- webclient - 这个 WebClient 和 HttpClient 实现有什么不同?