我猜进入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 代码中嵌入表达式的好方法是什么?