reactjs - 如何在返回函数中编写 IF 语句?
问题描述
这将是在线商店结帐屏幕的一部分,我正在尝试在退货中编写 if 语句,根据购物车中是否有产品来指示将向用户显示的内容。我的浏览器没有读取代码,它只是将所有代码作为纯文本插入到屏幕上,我不知道问题出在哪里。提前致谢
render() {
return (
<div>
if(this.context.cart.length === 0){
<div className="emptyCart">
<p>Your cart is empty right now, when you're done shopping return here to see it!</p>
</div>
}else{
<div className="cartTotal">
<label className="price">Total Price: ${this.getTotal()}</label>
</div>
}
</div>
);
}
解决方案
{
}
在分隔符(将 JSX 标记与 JavaScript 表达式分开)内,请改用条件运算符。
render() {
return (<div>{
this.context.cart.length === 0
? (
<div className="emptyCart">
<p>Your cart is empty right now, when you're done shopping return here to see it!</p>
</div>
) : (
<div className="cartTotal">
<label className="price">Total Price: ${this.getTotal()}</label>
</div>
)
}</div>);
}
推荐阅读
- visual-studio-2010 - Visual Studio 代码终端 - 类型错误:无法读取未定义的属性“执行”
- json - Flutter中的JSON数据到数组
- javascript - 带有 useEffect 钩子的无限滚动使用前一个参数值运行
- r - 运行多个“配对”t.tests 以比较 R 中数据框中的列值对
- c - 无法连接到c中的数据库
- sockets - 为什么 UDP 数据包被识别为 LLC 协议?
- python - 在 Windows 上安装 Pylucene
- html - 如何在没有空格的情况下将一列设置为彼此相邻?
- c# - 如何在 dot net core 中获取另一个时区的当地时间
- git - 我可以将哪些 Git 合并工具与自定义合并驱动程序一起使用?