我正在尝试根据我引入的数据中是否存在 JSON 键来隐藏或显示 HTML 元素。如果该键存在,我想显示我放入的元素 ID中的对象。如果键不存在,我想隐藏相同的元素 ID。我正在使用 React,但不确定它是否属于 componentDidMount 或常规函数。我是新手,所以如果我不小心遗漏了重要的代码或写了蹩脚的东西,我深表歉意。
我的 componentDidMount
代码:
componentDidMount = () => {
// Need to hide an the HTML element if the json key doesn't exist in the object
//check the JSON object for the key "workExamples"
if (typeof props.workItemData.workExamples === "undefined") {
console.log("it did not find the json key");
// Change element styling to hidden
document.getElementById("work-examples").style.visibility = "hidden";
} else {
return;
}
};
我的 HTML:
<span id="work-examples" className="work-examples">
<a href={props.workItemData.workExamples}>Work Examples</a>
</span>
我假设我不需要发布我的 JSON 对象。我有一些;只有一个具有 workExamples
键。我正在使用 .map()
来列出对象。
使用上面的代码,它不会为没有键的 JSON 对象隐藏列表中的元素。希望这一切都有意义。感谢您提供任何帮助。
最佳答案
正如 Luke 在评论中指出的那样,
the logic for whether or not to render should live in
render
这里的其他答案已经涵盖了这个机制,所以我不会一一赘述。
其他几点:
您正在尝试使用箭头函数来定义标准 React 函数 componentDidMount
,并且基于快速的本地测试,我认为 React 无法理解这一点。与传统的 componentDidMount() {/* do stuff here */}
语法相比,你似乎没有从中获得任何特别的好处,所以我会切换到后者。
您正在尝试检查您的 JSON 是否包含 key
typeof props.workItemData.workExamples === "undefined"
但我认为不需要typeof
;您可以直接检查 key 是否存在:
if(props.workItemData.workExamples) { /* do stuff */ }
最后,在您的 HTML 中,行
<a href={props.workItemData.workExamples}>Work Examples</a>
试图用来自 JavaScript 的值(花括号中的内容)设置 href
的值。这对 JSX 有效,这是有道理的,因为您使用的是 React,但不是纯 HTML。但是由于页面正在加载并且只是没有正确处理逻辑的某个部分,我假设你只是指你的 JSX 中的类似 HTML 的东西(一个 something.js
文件)而不是字面意思一个 HTML 文件。
关于javascript - 如果 React 中不存在 JSON 键,如何隐藏 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50221841/