2017-07-24 60 views
0

正確的語法我有一個布爾值,道具的反應,我想使用它,如下圖所示:陣營:什麼是布爾檢查

const MyComponent = ({ prop1, prop2, isBoolean }) => { 
...do something.. 
return (
if (isBoolean) ? (do this) : (do that) 
} 

,所以我說,如果isBoolean爲真,那麼這樣做別的去做。這是正確的語法嗎?

回答

0

如果要使用三元運算符,則必須刪除if關鍵字。

isBoolean ? (do this) : (do that) 

然後它確實是一個合適的語法。

0

不,它不是在JS正確的語法。您在一個聲明中混合使用了if聲明和tenary operator。正確的語法可以是:

  • 如果聲明

    if (isBoolean) { 
        //do this 
    } else { 
        //do that 
    } 
    
  • 或tenary操作

    isBoolean ? expression1 : expression2; 
    
0

沒有,要麼乾脆:

isBoolean ? this : that 

或者,對於更復雜的(多線)代碼:

if (isBoolean) { 
    this 
} else { 
    that 
} 
0

如果你想要做的return (expression),你將需要使用三元操作符內部條件呈現。

const MyComponent = ({ prop1, prop2, isBoolean }) => { 
    // ...do something.. 
    return (
     { isBoolean ? (do this) : (do that) } 
    ); 
}; 

你也可以return語句之前執行的條件如下:

const MyComponent = ({ prop1, prop2, isBoolean }) => { 
    // ...do something.. 

    const DOMToRender = isBoolean ? this : that; 

    return (
     { isBoolean ? (do this) : (do that) } 
    ); 
}; 

你也可以用和if/else語句repleace const DOMToRender = isBoolean ? this : that;

0

如果有可能在任何時候都未定義(即默認情況下),您可以通過雙重砰砰聲將它強制爲三元組的布爾值!

return !!isBoolean ? (do this) : (do that)