element.style为“”,并且在react中未正确设置

我正在尝试设置元素的样式,并在调试过程中在devtools中检查值时 例如,即使id this.props.offsetTop的值为95,也要获取值=“”。

import * as React from "react";
import * as ReactDOM from "react-dom";

type Props = {
  offsetTop: number;
  offsetLeft: number;
}

class Modal extends React.Component<Props> {
    el: any;
  constructor(props) {
    super(props);
    // @ts-ignore
    this.el = document.createElement("div");
    this.el.style.left = this.props.offsetLeft; //props.offsetLeft=495 
    this.el.style.top = this.props.offsetTop;    //el.style.left = "" value is still empty
  }

  componentDidMount() {
    // @ts-ignore
    document.getElementById("modal-root").appendChild(this.el);
  }

  componentWillUnmount() {
    // @ts-ignore
    document.getElementById("modal-root").removeChild(this.el);
  }

  render() {
    return ReactDOM.createPortal(
      this.props.children,
      // @ts-ignore
      this.el
    );
  }
}

const ModalRoot = () => <div id="modal-root" />;

export { Modal, ModalRoot};

评论
  • et_et
    et_et 回复

        this.el.style.left = this.props.offsetLeft + "px";
        this.el.style.top = this.props.offsetTop + "px";