React:渲染函数中的条件语句 [英] React: conditional statement in render function
本文介绍了React:渲染函数中的条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一系列不同艺术家的对象。我想根据图像是否在单个对象中显示不同的内容。
I have an array of objects with different artists. I want to show different content based on whether or not an image is in the individual object.
我试图将设为if / else
我的render方法中的语句,但当然这不起作用。请参阅下面的代码。
I have tried to put an if/else
statement in my render method, but of course this is not working. Please see my code below.
render: function() {
var cardList = this.props.artists.map(function(artist, index){
return(
<li key={index} className='card'>
<span>
{if artist.image}
<img src="{artist.image}">
{else}
<p>{artist.message}</p>
<p>LIKES <i className="fa fa-heart" aria-hidden="true"></i> {artist.likeCount }</p>
</span>
</li>
)
})
return (
<div className='tickerwrapper'>
<ul className='list'>{cardList}</ul>
</div>
)
}
推荐答案
您可以按照以下方式内联:
You can inline something along the lines of:
{ myVal === true ? <div>True</div> : <div>False</div> }
例如,如果 myVal 为真,你只想要呈现的东西如果它是假的,你可以返回null:
If, for example you only want something rendered if myVal is true you can do return null if it's false:
{ myVal === true ? <div>True</div> : null }
如果逻辑非常大,只需将其提取到一个函数中并从中调用它渲染:
If the logic is quite large just extract it into a function and call that from within your render:
renderSalutation() {
return (userLoggedOn ? <h3>Hello!</h3> : null);
}
render() {
return (
<div>
{ this.renderSalutation() }
------other renderings here
</div>
);
}
这篇关于React:渲染函数中的条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文