基本上,我有一个react组件,它的render()函数体如下所示:(这是我的理想之一,这意味着它目前不工作)

render(){
    return (
        <div>
            <Element1/>
            <Element2/>

            // note: logic only, code does not work here
            if (this.props.hasImage) <ElementWithImage/>
            else <ElementWithoutImage/>

        </div>
    )
}

当前回答

我用了一个三元运算符,它对我来说工作得很好。

{item.lotNum == null ? ('PDF'):(item.lotNum)}

其他回答

尝试使用Switch case或三元操作符

render(){
    return (
        <div>
            <Element1/>
            <Element2/>
            // updated code works here
            {(() => {
                        switch (this.props.hasImage) {
                            case (this.props.hasImage):
                                return <MyImage />;
                            default:
                                return (
                                   <OtherElement/>; 
                                );
                        }
                    })()}
        </div>
    )
}

这招对我管用,对你也适用。 尝试三元运算符

没有一个答案提到短路法

{this.props.hasImage && <MyImage />}

当然,如果你想在else逻辑上呈现一些东西,你就不能使用它。 我从react的例子中学到了这个

在更深入的扫描中,我确实看到了@ZekeDroid的评论,但我将把它作为答案,因为它可能有用。

是的,你可以在JSX渲染中使用条件。你可以在这里阅读更多。

语法:

condition ? exprIfTrue : exprIfFalse

条件声明必须如下所示,这里有一个例子:

return (
    <div>
      {condition  ? (
        //do some actions if condition is true
      ) : (
        //do some actions if condition is false
      )}
    </div>
)

if else结构的简写在JSX中可以正常工作

这个道具。hasImage ?<我的形象/>:< some therement >

你可以在DevNacho的这篇博客文章中找到其他选项,但更常见的是用速记。如果你需要一个更大的If子句,你应该写一个返回组件a或组件B的函数。

例如:

this.setState({overlayHovered: true});

renderComponentByState({overlayHovered}){
    if(overlayHovered) {
        return <OverlayHoveredComponent />
    }else{
        return <OverlayNotHoveredComponent />
    }
}

你可以从中解构你的overlayhovers。状态,如果你给它作为参数。然后在render()方法中执行该函数:

renderComponentByState(这个state university)。

你可以引入一个单独的方法来返回div元素并在return中调用它。我使用这种情况的例子,错误呈现取决于状态,如:

const renderError = () => {
    if (condition)
        return ....;
    else if (condition)
        return ....;
    else if (condition)
        return ....;
    else
        return ....;
}

render(){
   return (
     <div>
      ....
      {renderError()}
     </div>
   );
}