在 JSX 代码中嵌入 if 表达式的方法? [英] way to embed if expressions inside JSX code?

查看:64
本文介绍了在 JSX 代码中嵌入 if 表达式的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

所以这里的 if 语句是无效的:

return 

如果(某事){<ProjectType typ={this.state.type} onChange={this.changeType}/>}选择是 {type[this.state.type]}

;

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

return 

也许_render(东西,this.state.type,this.changeType)选择是 {type[this.state.type]}

;

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

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

解决方案

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

返回 (<div>{做一点事 ?东西:空}别的东西

);

I guess that stuff that goes into a react tag must be a react tag or a string; a function that returns a tag or string; a collection of tag or string or functions that return them.

So the if statement here is not valid:

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

So the obvious way is to move that if expression into a function maybe_render that returns the tag when the condition is met.

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

Problem is, some snippets will have lots of calls to functions that have very little logic. Instead of a 5-line snippet, we may have a 5-line snippet with many calls to extremely small functions.

What is a good way to embed if expressions inside JSX code?

解决方案

I usually do ternary if statements if there's not much logic or cause for re-use:

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

这篇关于在 JSX 代码中嵌入 if 表达式的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆