在 JSX 代码中嵌入 if 表达式的方法?

IT技术 reactjs
2021-04-19 10:18:49

我猜进入react标签的东西必须是react标签或字符串;一个返回标签或字符串的函数;标签或字符串或返回它们的函数的集合。

所以if这里声明是无效的:

return <div> 
        if(something){
           <ProjectType typ={this.state.type} onChange={this.changeType}/>
        }
        And the choice is {type[this.state.type]}
      </div>;

所以显而易见的方法是将该if表达式移动到一个函数中maybe_render该函数在满足条件时返回标签。

return <div> 
        maybe_render(something, this.state.type, this.changeType)
        And the choice is {type[this.state.type]}
      </div>;

问题是,一些代码片段会调用很多逻辑很少的函数。我们可能有一个 5 行代码段,而不是 5 行代码段,其中包含许多对极小函数的调用。

if在 JSX 代码中嵌入表达式的好方法是什么

1个回答

如果没有太多逻辑或重用的原因,我通常会使用三元 if 语句:

return (
    <div>
        {doSomething ? something : null}
        Something else
    </div>
);