React render 函数中可以使用 if...else... 语句吗?
P粉020556231
P粉020556231 2023-10-10 23:49:38
0
2
469

基本上,我有一个react组件,它的render()函数体如下:(这是我的理想组件,这意味着它目前不起作用)

render(){
    return (
        <div>
            <Element1/>
            <Element2/>

            // note: logic only, code does not work here
            if (this.props.hasImage) <ElementWithImage/>
            else <ElementWithoutImage/>

        </div>
    )
}


P粉020556231
P粉020556231

全部回复(2)
P粉985686557

实际上有一种方法可以完全满足OP的要求。只需渲染并调用匿名函数,如下所示:

render () {
  return (
    
{(() => { if (someCase) { return (
someCase
) } else if (otherCase) { return (
otherCase
) } else { return (
catch all
) } })()}
) }
P粉521013123

不完全一样,但有解决方法。 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.

}
);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!