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

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

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

        </div>
    )
}

当前回答

很多很棒的答案,但我还没有看到使用对象映射到不同的视图

const LOGS = {
  info: <Info />,
  warning: <Warning />,
  error: <Error />,
};
 
const Notification = ({ status }) => <div>{LOGS[status]}</div>

其他回答

你应该记住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>
    )
}

我不认为我看到这个解决方案的内联else if渲染,你有超过2个条件,所以我分享它:

{variable == 0 ?
  <Element1/>
:variable == 1 ?
  <Element2/>
:variable == 2 ?
  <Element3/>
:
  <Element4/>
}

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

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

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

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

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>}