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

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

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

        </div>
    )
}

当前回答

if then的简写

 { condition ? <Element1/> : null }

其他回答

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

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

如果你想使用If, else If和else则使用此方法

           {this.state.value === 0 ? (
                <Component1 />
            ) : this.state.value === 1 ? (
              <Component2 />
            ) : (
              <Component3 />
            )}

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

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

语法:

condition ? exprIfTrue : exprIfFalse

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

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

仅当:

{condition1 && 
(<div> condition1 true </div>)}

对于if和else:

{condition1 ? 
(<div> condition1 true </div>)
:(<div> condition1 false </div>)}

if, else if, else:

{condition1 ? 
(<div>condition1 true</div>)
:(condition2) && 
(<div>condition2 true</div>)
:(<div>both conditions false</div>)}