首页 > 解决方案 > 如何在返回函数中编写 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>
        );
    }

标签: reactjs

解决方案


{ }在分隔符(将 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>);
}

推荐阅读