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

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

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

        </div>
    )
}

当前回答

下面的代码,你可以使用的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 }

如果你有2个不同的依赖关系,你也可以在条件操作符中使用条件(三元)操作符。

{
(launch_success)
  ?
  <span className="bg-green-100">
    Success
  </span>
  :
  (upcoming)
    ?
    <span className="bg-teal-100">
      Upcoming
    </span>
    :
    <span className="bg-red-100">
      Failed
    </span>
}

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

语法:

condition ? exprIfTrue : exprIfFalse

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

return (
    <div>
      {condition  ? (
        //do some actions if condition is true
      ) : (
        //do some actions if condition is false
      )}
    </div>
)

if else结构的简写在JSX中可以正常工作

这个道具。hasImage ?<我的形象/>:< some therement >

你可以在DevNacho的这篇博客文章中找到其他选项,但更常见的是用速记。如果你需要一个更大的If子句,你应该写一个返回组件a或组件B的函数。

例如:

this.setState({overlayHovered: true});

renderComponentByState({overlayHovered}){
    if(overlayHovered) {
        return <OverlayHoveredComponent />
    }else{
        return <OverlayNotHoveredComponent />
    }
}

你可以从中解构你的overlayhovers。状态,如果你给它作为参数。然后在render()方法中执行该函数:

renderComponentByState(这个state university)。

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