繁体   English   中英

当存在具有该 ID 的元素时,为什么 document.getElementById() 返回 null?

[英]Why is document.getElementById() returning null when there is an element with that Id?

我正在尝试在 React 中构建一个导航栏,该导航栏有一个子组件Menu ,它根据菜单在其中呈现的 div 上的宽度呈现两个不同版本的菜单之一。 还有一个徽标和公司名称在导航栏中占据相对恒定的宽度,并且保存菜单的 div 会随着屏幕宽度和纵横比的变化而增长和缩小。 无论如何,那个增长和缩小的 div 我给了一个id="menu-section"以便我可以使用document.getElementById("menu-section").offsetWidth; 获取可用宽度并在决定渲染哪个版本的菜单的 function 中使用它。 问题是我得到一个TypeError: Cannot read property 'offsetWidth' of null 为什么document.getElementById("menu-section")找不到 div 并返回 null?

function Menu(props) {
    let availableWidthPx = document.getElementById("menu-section").offsetWidth;
    if (availableWidthPx > 600) {
        return expanded version;
    }
    return collapsed version
}

function Navbar(props) {
    render(){
        return (
            <nav className="navbar">
                ...
                <div id="menu-section">
                    <Menu />
                </div> 
            </nav>
        )
    }
}
export default Navbar;

因为 DOM 尚未加载。 以下是解决方法:

function Menu(props) {
  React.useEffect(() => {
    let availableWidthPx = document.getElementById("menu-section");
    if (availableWidthPx) {
      console.log(availableWidthPx.offsetWidth);
    }

  }, [])

 return <div>Hello</div>;
}

此外,您的Navbar功能组件只需要return ,而不是render

因为在所有渲染完成并将结果添加到 DOM 之前,没有具有该 ID 的元素……但是您正试图从 render 方法中调用它。

您还应该考虑在渲染后调用菜单 function,或者在afterRender()块中定义它。

Navbar导航栏不会向 DOM 添加任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM