ReactJS 条件渲染 - 否则如果不起作用



我正处于学习JS和React的阶段,我不知道为什么在下面的代码中不起作用。有人能帮我吗?

function Item({ name, isPacked }) {
if (isPacked) {
return (
<li className="item">
{name} {isPacked && " ✔"}
</li>
);
} else if (!isPacked) {
return (
<li className="item">
{name} {isPacked && " ❌"}
</li>
);
}
}
export default function PackingList() {
return (
<section>
<h1>Sally Ride's Packing List</h1>
<ul>
<Item isPacked={true} name="Space suit" />
<Item isPacked={true} name="Helmet with a golden leaf" />
<Item isPacked={false} name="Photo of Tam" />
</ul>
</section>
);
}

这样尝试:

function Item({ name, isPacked }) {
return (
<li className="item">
{name} {isPacked ? '✔' : '❌'}
</li>
);
}

您实际测试了isPacked是真是假,所以请尝试以下代码:

function Item({ name, isPacked }) {
return (
<li className="item">
{name}  {isPacked ? "✔" : "❌" }
</li>
);
}

{isPacked?"✔":"❌"}所以这行代码等于:

if(isPacked == true){
return "✔";
}else{
return "❌";
}

你可以在这里得到一些有用的例子https://reactjs.org/docs/conditional-rendering.html.

最新更新