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

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

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

        </div>
    )
}

当前回答

我找到了一个我认为比“如果-否则”更好的解决方案。应该使用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或三元操作符更简洁。

其他回答

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

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

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

我用了一个三元运算符,它对我来说工作得很好。

{item.lotNum == null ? ('PDF'):(item.lotNum)}

你也可以写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>

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)。

四种条件渲染方式

(在功能组件的返回语句或类组件的渲染函数的返回语句中)

 

三元运算符

 

return (
    <div>     
        {
            'a'==='a' ? <p>Hi</p> : <p>Bye</p>
        } 
    </div>
)

注意:只有条件'a'==='a'为真时,<p>Hi</p>才会在屏幕上显示。否则,<p>Bye</p>将显示在屏幕上。

 

逻辑运算符

 

和& &

return (
    <div>     
        {
            'a'==='a' && <p>Hi</p>
        } 
    </div>
)

注意:只有条件'a'==='a'为真时,<p>Hi</p>才会在屏幕上显示。

 

或| |

export default function LogicalOperatorExample({name, labelText}) {
    
  return (
    <div>       
         {labelText || name}      
    </div>
  )
}

注意:如果labelText和name两个道具都被传递到这个组件中,那么labelText将在屏幕中呈现。但如果只有一个(name或labelText)作为道具传递,那么传递的道具将在屏幕中呈现。

 

如果,否则,否则如果

 

return ( 
        <div>     
            {
                (() => {
                    if('a'==='b') {
                            return (
                                <p>Hi</p>
                            )
                        } else if ('b'==='b') {
                            return (
                            <p>Hello</p>
                            )
                        } else {
                            return (
                                <p>Bye</p>
                            )
                        }
                })()  
            }  
        </div>  
    )

注意:必须使用匿名函数(还需要立即调用该函数)

 

Switch语句

 

return ( 
    <div>     
        {
            (() => {
                switch(true) {
                        
                    case('a'==='b'): {
                            return (
                                <p>Hello</p>
                            )
                        }
                    break;
                        
                    case('a'==='a'): {
                        return (
                            <p>Hi</p>
                        )
                    }
                    break;
                    
                    default: {
                            return (
                                <p>Bye</p>
                            )
                        }
                    break;
                    }
            })()  
        }  
    </div>  
)

注意:必须使用匿名函数(还需要立即调用该函数)