首页 > 解决方案 > 反应中心 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>
        )


    }
}

让我知道你的想法

标签: javascriptreactjs

解决方案


好的,使用 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 });

推荐阅读