简体   繁体   English

JSX中的条件渲染

[英]Conditional Rendering in JSX

How can I do a conditional rendering with JSX? 如何使用JSX进行条件渲染?

for instance I have div here where I want to render the text "NO IDEA" if the value of the props in null otherwise render the props if its not equal to null. 例如,我在这里有div,如果props的值为null,则要渲染文本“ NO IDEA”,否则,如果其不等于null,则渲染props。

For example: 例如:

<div>{ return this.props.date === null ? 'NO IDEA' : this.props.date }</div>

I tried this but it did not worked out. 我尝试了一下,但没有成功。 Any idea what am doing wrong here? 知道这里做错了什么吗?

Thanks in advance! 提前致谢!

您可以仅基于this.props.date使用三元运算符,因此您无需在此处返回

<div> {this.props.date === null ? 'NO IDEA' : this.props.date }</div>

First of all, you don't need to use return statement inside the expression block. 首先,您不需要在表达式块内使用return语句。 Next thing, don't check just for null , it might be undefined rather: 接下来,不要只检查null ,而是可能undefined

<div>{ this.props.date ? this.props.date : 'NO IDEA' }</div> 

This simply checks if date is available / true parsed in boolean, then use true value else use false value. 这只是检查date是否可用/布尔值中解析为true,然后使用true值,否则使用false值。

Or, even in simpler syntax using || 或者,甚至使用||以更简单的语法 :

{ this.props.date || 'NO IDEA' }

This will render the date only if date value is true parsed in boolean otherwise it will render 'NO IDEA'. 仅当布尔值中解析的date值为true时,才会呈现日期,否则将呈现“ NO IDEA”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM