我正在使用 JavaScript 对象,并尝试根据布尔值呈现按钮,但遇到了问题。这是我的代码片段:
const toy_material = toy.material.allow; // This is a boolean value that can be true, false, undefined, or null
console.log("toy_material", toy_material);
当我 console.log("toy_material", toy_material) 时,控制台中没有显示任何内容。我还尝试根据 toy_material 的值有条件地渲染按钮。我希望无论 toy_material 是 true、false、undefined 还是 null,按钮都会显示。
我怎样才能实现这个目标?任何帮助将不胜感激!
提前致谢!
我尝试使用 console.log("toy_material", toy_material); 记录该值但控制台中没有打印任何内容。我希望它记录该值,无论该值是 true、false、未定义还是 null,这样我就可以使用该值有条件地呈现按钮。我希望按钮在所有情况下都能呈现,无论布尔值是什么。我如何实现这一目标?
首次使用?具有对象属性的运算符有助于管理 null、undefiend
const toy_material = toy?.material?.allow;
为了渲染按钮,如果
toy_material
为 true,则显示按钮,否则在 null、未定义和 false 的情况下不会显示任何内容。这是您可以做到的方法。
return (
<div>
{ toy_material && <button>click here!</button> }
</div>
)
我希望它对你有用。