在React JSX中使用if语句 [英] Use if statement in React JSX

查看:669
本文介绍了在React JSX中使用if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以像这样在JSX中使用if语句吗?

Can you use a if statement in JSX like this?

    var chartGraphContent =
        <div className={"chartContent"}>
            if(this.state.modalityGraph['nca'] > 0){
                <div className={"chart-container"}>
                    <Chart
                        chartType="ColumnChart"
                        data = { this.state.modalityGraph?this.state.modalityGraph.chartData['units']:emptyDataRows }
                        options={chartOptions}
                        graph_id="modalitiesChart"
                        width="100%"
                        height="250px"
                    /> 
                </div>
            }
        </div>;

像上面一样?可以根据条件使用JSX吗?

Something like above? Is it possible to have JSX based on a condition?

推荐答案

使用有条件的渲染,并且由于没有其他情况,因此为了简洁起见,可以使用&&而不是三元运算符:

Use conditional rendering, and since you have no else-case, you can use && instead of a ternary operator for brevity:

它之所以有效,是因为在JavaScript中,true && expression总是计算为expression,而false && expression总是计算为false.

It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

因此,如果条件为true,则&&之后的元素将出现在输出中.如果为假,React将忽略并跳过它.

Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

因此:

   <div className={"chartContent"}>
        {this.state.modalityGraph['nca'] > 0 &&
            <div className={"chart-container"}>
                <Chart
                    chartType="ColumnChart"
                    data = { this.state.modalityGraph?this.state.modalityGraph.chartData['units']:emptyDataRows }
                    options={chartOptions}
                    graph_id="modalitiesChart"
                    width="100%"
                    height="250px"
                /> 
            </div>
        }
    </div>

这仅在条件为true时才呈现JSX.如果为假,React将不会渲染任何内容.请记住,您必须使用{ … }将内联JavaScript表达式包装在JSX中,而不仅仅是将其包含在JSX中.

This will only render JSX if a condition is true. If it is false, React won't render anything. Remember, you have to wrap inline JavaScript expressions in JSX with { … }, you can't just have it inside JSX.

如果直接使用if/else语句是JSX,则将其直接显示为文本,这是不希望的.您也不能在嵌入式JavaScript表达式中使用它们,因为如果声明不是表达式,那么此无效:

Using if/else statements directly is JSX will cause it to be rendered literally as text, which isn't desired. You also can't use them in inline JavaScript expressions because if statements are not expressions, so this won't work:

{
  if(x) y
}

这篇关于在React JSX中使用if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆