基本上,我有一个react组件,它的render()函数体如下:(这是我理想的一个,这意味着它目前不起作用)
render(){
return (
<div>
<Element1/>
<Element2/>
// note: logic only, code does not work here
if (this.props.hasImage) <ElementWithImage/>
else <ElementWithoutImage/>
</div>
)
}
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
实际上有一种方法可以完全满足OP的要求。只需渲染并调用匿名函数,如下所示:
render () { return ( <div> {(() => { if (someCase) { return ( <div>someCase</div> ) } else if (otherCase) { return ( <div>otherCase</div> ) } else { return ( <div>catch all</div> ) } })()} </div> ) }