我正在尝试在元素甚至在dom上渲染之前测量其高度。我有下面的mesureElement()
函数,该函数只给我宽度(浏览器宽度)和高度,始终为0。
我在做什么错了?
import React from "react";
import ReactDOM from "react-dom";
const containerStyle = {
overflow: "hidden",
display: "inline-block"
};
const measureElement = () => {
const container = document.createElement("div");
container.style = containerStyle;
document.body.appendChild(container);
ReactDOM.createPortal(<div style={{ height: "500px" }} />, container);
const height = container.clientHeight;
const width = container.clientWidth;
console.log(width); // browser width
console.log(height); // 0
ReactDOM.unmountComponentAtNode(container);
return { height, width };
};
export default measureElement;
提前谢谢!
答案 0 :(得分:0)
ReactDOM.createPortal()
仅在渲染方法中按预期工作。
改为尝试ReactDOM.render
:
const measureElement = () => {
const container = document.createElement("div");
//container.style = containerStyle;
document.body.appendChild(container);
//ReactDOM.createPortal(<div style={{ height: "500px" }} />, container);
ReactDOM.render(<div style={{ height: "500px" }} />, container);
const height = container.clientHeight;
const width = container.clientWidth;
console.log(width); // browser width
console.log(height); // should be 500
ReactDOM.unmountComponentAtNode(container);
return { height, width };
};
此外,您不能以这种方式将样式应用于HTMLElement:
const container = document.createElement("div");
container.style = containerStyle;
HTMLElement.style
是只读属性;