基本上,我有一个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的评论,但我将把它作为答案,因为它可能有用。

其他回答

我找到了一个我认为比“如果-否则”更好的解决方案。应该使用2条return语句。看到的例子:

render() {
    const isLoggedIn = this.state.isLoggedIn;

    if (isLoggedIn) {
        return <LogoutButton onClick={this.handleLogoutClick} />
    }

    // This will never occur if the user is logged in as the function is returned before that.
    return <LoginButton onClick={this.handleLoginClick} />
}

这比在return语句中使用if-else或三元操作符更简洁。

你也可以写If语句组件。这是我在我的项目中使用的。

组件/ IfStatement.tsx

import React from 'react'

const defaultProps = {
    condition: undefined,
}

interface IfProps {
    children: React.ReactNode
    condition: any
}

interface StaticComponents {
    Then: React.FC<{ children: any }>
    Else: React.FC<{ children: any }>
}

export function If({ children, condition }: IfProps): any & StaticComponents {
    if (React.Children.count(children) === 1) {
        return condition ? children : null
    }

    return React.Children.map(children as any, (element: React.ReactElement) => {
        const { type: Component }: any = element

        if (condition) {
            if (Component.type === 'then') {
                return element
            }
        } else if (Component.type === 'else') {
            return element
        }

        return null
    })
}

If.defaultProps = defaultProps

export function Then({ children }: { children: any }) {
    return children
}

Then.type = 'then'

export function Else({ children }: { children: any }) {
    return children
}

Else.type = 'else'

If.Then = Then as React.FC<{ children: any }>
If.Else = Else as React.FC<{ children: any }>

export default If

使用的例子:

<If condition={true}>
   <If.Then>
        <div>TRUE</div>
   </If.Then>
   <If.Else>
        <div>NOT TRUE</div>
   </If.Else>
</If>

没有一个答案提到短路法

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

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

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

if then的简写

 { condition ? <Element1/> : null }

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

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