我猜进入function标记的东西必须是function标记或字符串;返回标记或字符串的函数;返回它们的标记或字符串的集合。
因此,此处的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行代码段,其中包含了对非常小的函数的多次调用。
在JSX代码中嵌入if表达式的好方法是什么?
发布于 2015-07-14 10:45:29
如果没有太多的逻辑或重复使用的原因,我通常使用三元if语句:
return (
<div>
{doSomething ? something : null}
Something else
</div>
);https://stackoverflow.com/questions/31404038
复制相似问题