如果数组有值并且存在,我只想将数组值呈现为元素。在我的例子中,有一个颜色数组,用户可以设置当前的 color_theme,它由它的索引表示。开始时不应选择 color_theme。我的渲染函数将尝试渲染当前的 color_color_theme,但没有 current_color_index。如何在渲染前检查是否存在现有的颜色主题?我无法在重新渲染之前编写返回,因为还有其他元素必须渲染。
data = {
"colorthemes" : [ ["blue","red"], ["black","grey"] ],
"current_color_index": "",
....//more
}
render: function() {
return (
<div>
<ul>
//other stuff is rendering
</ul>
<ul>
{this.state.data.colorthemes[this.state.data.current_color_index].map(function(item, i) {
....
}, this)}
</ul>
</div>
最佳答案
只需在 jsx
中使用 if 条件,例如
{
condition ?
<MyRenderElement /> :
null
}
如果不满足条件,该代码块将不会呈现任何内容。
建议:我建议您使用合理的默认值,而不是使用这样的 if 条件。帮助您保留更少的控制流路径和更少的错误。
关于javascript - ReactJS : Only render element if array has values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938844/