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

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

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

        </div>
    )
}

当前回答

实际上有一种方法可以完全满足OP的要求。只需要像这样渲染和调用一个匿名函数:

render () {
  return (
    <div>
      {(() => {
        if (someCase) {
          return (
            <div>someCase</div>
          )
        } else if (otherCase) {
          return (
            <div>otherCase</div>
          )
        } else {
          return (
            <div>catch all</div>
          )
        }
      })()}
    </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)。

如果[…Else if], Else 在React返回函数中检查不止一次?

{Element1? (<Element1/>) : Element2 ? (<Element2/>) : Element3 ? (<Element3/>) : Element... ? (<Element.../>) : (<ElementLast />)}

if then的简写

 { condition ? <Element1/> : null }

没有一个答案提到短路法

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

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

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

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

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