【问题标题】:how do I run the this condition properly in Reactjs?如何在 Reactjs 中正确运行此条件?
【发布时间】:2021-06-29 23:37:36
【问题描述】:

** ReactJs **

    let resultDisplay=""
    if(Bmi>=18 || Bmi<=25 )
     {resultDisplay= <p>Perfect</p> 
    }

Problem is right there but I can't figure it out since I new in React

    else if(Bmi<18)
      resultDisplay=<p>to Thin</p>

``对我来说看起来不错,任何指导和帮助都会很棒```

    else if(Bmi>25)
      resultDisplay=<p>Overweight</p>
      setresult(resultDisplay)
    
}

Right now its only working on one condition and doesn't rendering the other conditions results

【问题讨论】:

    标签: reactjs function if-statement return


    【解决方案1】:

    简洁的方法...

    import React from "react";
    
    function App() {
        let Bmi = 23; // some value you assigned
    
        let resultDisplay = ""; //to display BMI result
    
        if (Bmi < 18)
            resultDisplay = "Too thin"; //Less than 18 means too thin
        else if (Bmi <= 25)
            resultDisplay = "Perfect"; //otherwise >= 18 && <= 25
        else
            resultDisplay = "Overweight"; //otherwise > 25
    
        return (
            <div>
                <p>{resultDisplay}</p>
                {/*Wrapping by curly braces to use the javascript variable inside the JSX*/}
            </div>
        );
    }

    【讨论】:

      【解决方案2】:

      这取决于您如何构建组件,但在渲染中使用三元会更简单。

      假设它是一个单一的值,在你的状态,(最常见的问题),或者来自一个函数,在你的渲染的返回你可以做类似的事情

      return(
      <p>
      {
      Bmi>=18 || Bmi<=25 //if
       ? 'Perfect' //then
       : Bmi < 18 //else if else
        ? 'to Thin' //then
        :Bmi > 25 //else if else
         ? 'too heavy' //then
         : '' //it's your last else if so else is empty
      : '' //last else of first if
      }
      </p>
      )
      

      【讨论】:

      • 谢谢你们,我的问题已经解决了
      【解决方案3】:

      var resultDisplay 是一个字符串,因此它不是 jsx 元素,将结果保存到字符串并将其包含在 jsx 中: 你的代码

      let resultDisplay=""
          if(Bmi>=18 || Bmi<=25 )
           {resultDisplay= '<p>Perfect</p>'
          }
      

      你在哪里展示它:

      <yourcomponent>{resultDisplay}<yourcomponent>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2020-02-10
        • 1970-01-01
        • 1970-01-01
        • 2020-01-14
        • 2018-11-14
        • 1970-01-01
        相关资源
        最近更新 更多