首页 > 解决方案 > 如果不为空,则反应分配值

问题描述

当我执行以下操作时:

let ContentAreaHeight = document.getElementById('contentArea').clientHeight;

我收到Cannot read property 'clientHeight' of null错误,第一次加载页面,我收到此错误是正常的。所以,我试图提出一个空值检查,如果不为空值,就像下面的选项之一一样,但两者都不起作用,仍然给出同样的错误。

选项1

let ContentAreaHeight = (document.getElementById('contentArea').clientHeight) || 0;

选项2

let ContentAreaHeight = (document.getElementById('contentArea').clientHeight !== null) ?
                    document.getElementById('contentArea').clientHeight : 0;

我搜索了很多地方都没有找到解决方案,这似乎很容易但没有什么真正有效..

我将此代码放在 const content = ({ pageURL, dataStatus }) => { 和 之间return (

标签: reactjsconditional

解决方案


你应该在打电话之前检查.clientHeight

let ContentAreaHeight = document.getElementById('contentArea');
if (ContentAreaHeight) ContentAreaHeight = ContentAreaHeight.clientHeight

推荐阅读