React & Next js:仅当 prop 包含值时才渲染 div

我正在完成我的应用程序,但我遇到了一个问题。

我有一些来自 contentful 的数据,我将它们作为道具传递给了我的组件。有一个数据,如果它包含任何值,我只想呈现它。

这项工作在某种程度上,但背景仍然显示。


<div classname="text-white font-base text-xs text-center p-1.5 bg-black">
   {`${mrr ? mrr : ""}`}
</div>

picture of the frontend

picture of the frontend 2

如果有人能帮忙,那就太好了。

yiling3716416 回答:React & Next js:仅当 prop 包含值时才渲染 div

@著名的lastwords TopW3 的答案是正确的。我会尽量解释代码。

仅当 mrr 为真时才会呈现以下文本。与执行以下代码相同:

const result = true && anything; // result = anything

const result = false && anything // result = false

{mrr && (
    <div className="text-white font-base text-xs text-center p-1.5 bg-black">
        {mrr}
    </div>
)}
,

试试这个代码。

{mrr && (
    <div className="text-white font-base text-xs text-center p-1.5 bg-black">
        {mrr}
    </div>
)}
本文链接:https://www.f2er.com/5064.html

大家都在问