React render 函數中可以使用 if...else... 語句嗎?
P粉020556231
P粉020556231 2023-10-10 23:49:38
0
2
480

基本上,我有一個react元件,它的render()函數體如下:(這是我的理想元件,這意味著它目前不起作用)

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

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

        </div>
    )
}


#
P粉020556231
P粉020556231

全部回覆(2)
P粉985686557

其實有一種方法可以完全滿足OP的要求。只需渲染並呼叫匿名函數,如下所示:

render () {
  return (
    
{(() => { if (someCase) { return (
someCase
) } else if (otherCase) { return (
otherCase
) } else { return (
catch all
) } })()}
) }
P粉521013123

不完全一樣,但有解決方法。 React 文件中有一個關於條件渲染的部分,您應該看一下。以下是使用內聯 if-else 可以執行的操作的範例。

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    
{isLoggedIn ? ( ) : ( )}
); }

您也可以在渲染函數內處理它,但在傳回 jsx 之前。

if (isLoggedIn) {
  button = ;
} else {
  button = ;
}

return (
  
{button}
);

也值得一提的是 ZekeDroid 在評論中提出的內容。如果您只是檢查條件並且不想呈現不符合條件的特定程式碼段,則可以使用 && 運算子

return (
    

Hello!

{unreadMessages.length > 0 &&

You have {unreadMessages.length} unread messages.

}
);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!