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

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

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

        </div>
    )
}

当前回答

没有一个答案提到短路法

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

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

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

其他回答

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

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

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

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

如果你需要不止一个条件,那么你可以试试这个

https://www.npmjs.com/package/react-if-elseif-else-render

import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';

class Example extends Component {

  render() {
    var i = 3; // it will render '<p>Else</p>'
    return (
      <If condition={i == 1}>
        <Then>
          <p>Then: 1</p>
        </Then>
        <ElseIf condition={i == 2}>
          <p>ElseIf: 2</p>
        </ElseIf>
        <Else>
          <p>Else</p>
        </Else>
      </If>
    );
  }
}

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

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

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

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

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