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

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

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

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

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

其他回答

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

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();
}}

这对我很有用。:)

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

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

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

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

下面的代码,你可以使用的If条件反应在侧返回

                                    {(() => {if (true) {return ( <div><Form>
                                        <Form.Group as={Row} style={{ marginLeft: '15px', marginRight: '15px', marginBlock: '0px' }} >
                                            <Form.Label className="summary-smmdfont" style={{ flex: '1 0 auto', marginBlock: '0px' }}>   uyt</Form.Label>
                                            <Form.Label className="summary-smmdfont"style={{ textAlignLast: 'Right', flex: '1 0 auto', marginBlock: '0px' }}>
                                                09</Form.Label>
                                        </Form.Group>
                                        </Form>

                                    </div>);
                    }})()}

if then的简写

 { condition ? <Element1/> : null }