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

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

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

        </div>
    )
}

当前回答

也许我来晚了。但我希望这能帮助到一些人。首先分离这两个元素。

renderLogout(){
<div>
   <LogoutButton onClick={this.handleLogoutClick} />
<div>
}

renderLogin(){
<div>
   <LoginButton onClick={this.handleLoginClick} />
<div>
}

然后你可以使用if else语句从render function调用这些函数。

render(){
if(this.state.result){
  return this.renderResult();
}else{
  return this.renderQuiz();
}}

这对我很有用。:)

其他回答

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

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

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

如果您想要一个条件来显示元素,您可以使用类似这样的东西。

renderButton() {
    if (this.state.loading) {
        return <Spinner size="small" spinnerStyle={styles.spinnerStyle} />;
    }

    return (
        <Button onPress={this.onButtonPress.bind(this)}>
            Log In
        </Button>
    );
}

然后调用渲染函数中的帮助方法。

<View style={styles.buttonStyle}>
      {this.renderButton()}
</View>

或者你也可以用另一种方法在return中设置条件。

{this.props.hasImage ? <element1> : <element2>}

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

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

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

render () {
  return (
    <div>
      {(() => {
        if (someCase) {
          return (
            <div>someCase</div>
          )
        } else if (otherCase) {
          return (
            <div>otherCase</div>
          )
        } else {
          return (
            <div>catch all</div>
          )
        }
      })()}
    </div>
  )
}

类型1:If语句样式

{props.hasImage &&

  <MyImage />

}

类型2:If else语句样式

   {props.hasImage ?

      <MyImage /> :

      <OtherElement/>

    }