基本上,我有一个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-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
实际上有一种方法可以完全满足OP的要求。只需渲染并调用匿名函数,如下所示:
render () { return (
{(() => {
if (someCase) {
return (
someCase
)
} else if (otherCase) {
return (
otherCase
)
} else {
return (
catch all
)
}
})()}
)
}不完全一样,但有解决方法。 React 文档中有一个关于条件渲染的部分,您应该看一下。以下是使用内联 if-else 可以执行的操作的示例。
render() { const isLoggedIn = this.state.isLoggedIn; return (
{isLoggedIn ? (
) : (
)}
);
}您还可以在渲染函数内处理它,但在返回 jsx 之前。
if (isLoggedIn) { button = ;
} else {
button = ;
}
return (
{button}
);还值得一提的是 ZekeDroid 在评论中提出的内容。如果您只是检查条件并且不想呈现不符合条件的特定代码段,则可以使用
&& 运算符。return (
);Hello!
{unreadMessages.length > 0 &&You have {unreadMessages.length} unread messages.
}