簡體   English   中英

React - 使用 Switch 和 boolean 案例的條件渲染

[英]React - Conditional Rendering with Switch and boolean case

我想澄清一個關於 React Conditional Rendering with Switch Case 的疑問

我有一個有條件的實現。 即我必須根據 boolean 大小寫設置一個字符串值

例如

 let str = "";
    
    switch(some object)
    {
     case object.yes:  // The case here is boolean. IS it possible to set boolean case. I did try but the value is not set correctly based on the case in the str variable.
       str = "Yes"
    break:
    case object.no:
    str = "No"
    break;
    }

如果上面的代碼不可能,我會使用 if...else。 但是在代碼審查期間,我肯定會被問到為什么我不使用 Switch 而不是 if...else。 我想給出一個令人信服的答案。 我搜索了教程,但我只能找到字符串大小寫,而不是 React 的 boolean 大小寫。

只想驗證 boolean 案例是否可能。

最干凈的解決方案是使用IIFE

 const object = { yes: true, no: false } const str = (() => { switch (true) { case object.yes: // The case here is boolean. IS it possible to set boolean case. I did try but the value is not set correctly based on the case in the str variable. return "Yes"; case object.no: return "No"; default: return "Unknown"; } })(); console.log(str);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM