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

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

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

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

其他回答

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

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

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

仅当:

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

不完全是那样,但也有变通办法。React文档中有一节是关于条件渲染的,你应该看一看。下面是一个使用内联if-else的示例。

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <LogoutButton onClick={this.handleLogoutClick} />
      ) : (
        <LoginButton onClick={this.handleLoginClick} />
      )}
    </div>
  );
}

您也可以在渲染函数中处理它,但在返回jsx之前。

if (isLoggedIn) {
  button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
  button = <LoginButton onClick={this.handleLoginClick} />;
}

return (
  <div>
    <Greeting isLoggedIn={isLoggedIn} />
    {button}
  </div>
);

值得一提的是,ZekeDroid在评论中提到了这一点。如果你只是检查一个条件,不想呈现不符合条件的特定代码段,你可以使用&&操作符。

  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );