[英]React: conditional statement in render function
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.
我想根据图像是否在单个对象中显示不同的内容。
I have tried to put an if/else
statement in my render method, but of course this is not working. 我试图在我的render方法中放置一个
if/else
语句,但是当然这不起作用。 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> }
If, for example you only want something rendered if myVal is true you can do return null if it's false: 例如,如果您只想在myVal为true时呈现某些内容,则可以在false的情况下返回null:
{ 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>
);
}
You need to use a valid expression in your JSX code. 您需要在JSX代码中使用有效的表达式。 an if-else-statement is not, however you can use a ternary operator:
if-else-statement不是,但是您可以使用三元运算符:
var cardList = this.props.artists.map(function(artist, index) {
return(
<li key={index} className='card'>
<span>
{artist.image ? (
<img src="{artist.image}">
) : (
<p>{artist.message}</p>
<p>LIKES <i className="fa fa-heart" aria-hidden="true"></i> {artist.likeCount}</p>
)}
</span>
</li>
)
})
You can find more info on conditional rendering in the react docs . 您可以在react docs中找到有关条件渲染的更多信息。
It can be done with if/else. 可以使用if / else完成。 As shown on React site:
如React网站所示:
function NumberDescriber(props) {
let description;
if (props.number % 2 == 0) {
description = <strong>even</strong>;
} else {
description = <i>odd</i>;
}
return <div>{props.number} is an {description} number</div>;
}
Just do something similar in your render function. 只需在渲染函数中执行类似的操作即可。 Conditionally set a value to a component you want and then render it within {}.
有条件地为您想要的组件设置一个值,然后在{}中呈现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.