小编典典

表达式是否嵌入JSX代码内的方法?

reactjs

我想反应标签中的内容必须是反应标签或字符串。返回标签或字符串的函数;标签或字符串或返回它们的函数的集合。

因此,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代码的好方法是什么?


阅读 274

收藏
2020-07-22

共1个答案

小编典典

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

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