如何检查反应 jsx 中的条件?
How can I check condition in reactjsx?
刚开始查看 reactjsx 并尝试检查数组 (this.state.content) 是否未定义且长度 > 0。这是渲染方法的一部分:
display = (
<section>
{
if (this.state.content.length >0)
{
this.state.content.map((item, i) => {
return <CardRenderer addPacks={true} key={i} container={item}/>
})
}
}
</section>
)
但这不起作用,我如何才能在 jsx 中首先检查这个数组长度?
尝试:
display = (
<section>
{
this.state.content && this.state.content.map((item, i) => {
return <CardRenderer addPacks={true} key={i} container={item}/>
})
}
</section>
)
如果 this.state.content
未定义,&&
将短路映射,如果 this.state.content
的长度为零,映射将不执行任何操作(但不会出错).
你可以使用三元运算符
display = (
<section>
{
(this.state.content && this.state.content.length > 0)?
{
this.state.content.map((item, i) => {
return <CardRenderer addPacks={true} key={i} container={item}/>
})
} : null
}
</section>
)
刚开始查看 reactjsx 并尝试检查数组 (this.state.content) 是否未定义且长度 > 0。这是渲染方法的一部分:
display = (
<section>
{
if (this.state.content.length >0)
{
this.state.content.map((item, i) => {
return <CardRenderer addPacks={true} key={i} container={item}/>
})
}
}
</section>
)
但这不起作用,我如何才能在 jsx 中首先检查这个数组长度?
尝试:
display = (
<section>
{
this.state.content && this.state.content.map((item, i) => {
return <CardRenderer addPacks={true} key={i} container={item}/>
})
}
</section>
)
如果 this.state.content
未定义,&&
将短路映射,如果 this.state.content
的长度为零,映射将不执行任何操作(但不会出错).
你可以使用三元运算符
display = (
<section>
{
(this.state.content && this.state.content.length > 0)?
{
this.state.content.map((item, i) => {
return <CardRenderer addPacks={true} key={i} container={item}/>
})
} : null
}
</section>
)