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

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

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

        </div>
    )
}

当前回答

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

语法:

condition ? exprIfTrue : exprIfFalse

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

return (
    <div>
      {condition  ? (
        //do some actions if condition is true
      ) : (
        //do some actions if condition is false
      )}
    </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>
  )
}

我找到了一个我认为比“如果-否则”更好的解决方案。应该使用2条return语句。看到的例子:

render() {
    const isLoggedIn = this.state.isLoggedIn;

    if (isLoggedIn) {
        return <LogoutButton onClick={this.handleLogoutClick} />
    }

    // This will never occur if the user is logged in as the function is returned before that.
    return <LoginButton onClick={this.handleLoginClick} />
}

这比在return语句中使用if-else或三元操作符更简洁。

你应该记住TERNARY运算符

:

你的代码是这样的,

render(){
    return (
        <div>
            <Element1/>
            <Element2/>
            // note: code does not work here
            { 
               this.props.hasImage ?  // if has image
               <MyImage />            // return My image tag 
               :
               <OtherElement/>        // otherwise return other element  

             }
        </div>
    )
}

尝试使用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>
    )
}

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

if then的简写

 { condition ? <Element1/> : null }