admin管理员组文章数量:1387310
I understand how to use it in simple situations:
{(this.state.show) ? <span>Show</span> : null}
But how to use it for big DOM?
{ if (this.state.show) {
<span className={this.state.className}>Hi</span>
{this.state.text}
} else {
{this.state.text}
}
}
Of course, it doesn't work. How to do it correctly?
I understand how to use it in simple situations:
{(this.state.show) ? <span>Show</span> : null}
But how to use it for big DOM?
{ if (this.state.show) {
<span className={this.state.className}>Hi</span>
{this.state.text}
} else {
{this.state.text}
}
}
Of course, it doesn't work. How to do it correctly?
Share Improve this question edited Jan 30, 2016 at 18:13 Dmitry Shvedov 3,3164 gold badges40 silver badges56 bronze badges asked Feb 6, 2015 at 0:51 Nick BolshNick Bolsh 1501 gold badge3 silver badges15 bronze badges3 Answers
Reset to default 6You can't do that. I see two potential problems from what you've provided. First, you can only return one DOM node. Second, (and this might be because it's not your full code), your braces are not syntactically correct. Without knowing your full source code, you can try something like:
render: function() {
var header;
if (this.state.show) {
header = <span className={ this.state.className }>Hi</span>;
}
return <div>
{ header }
{ this.state.text }
</div>
}
Another way of doing if-else can be done by use of an IIFE as suggested here: https://facebook.github.io/react/tips/if-else-in-JSX.html.
{(() => {
if (this.state.show) {
<span className={this.state.className}>Hi</span>
{this.state.text}
} else {
{this.state.text}
}
})()}
Firstly you cannot use multiple ponents in one statement. You must do like this:
if (this.state.show) {
<span>
<span className={this.state.className}>Hi</span>
{this.state.text}
</span>
} else {
{this.state.text}
}
Ok, for big DOM, just like this:
{() => {
{ if (this.state.show) {
<span>
<span className={this.state.className}>Hi</span>
{this.state.text}
</span>
} else {
{this.state.text}
}
}}
or
{ this.state.show ? (
<span>
<span className={this.state.className}>Hi</span>
{this.state.text}
</span>
) : (
{this.state.text}
)
}
BTW, I have created a small library to do a lisp style if - else
import { _if } from 'jsxcond';
...
{ _if( this.state.show,
() => (
<span>
<span className={this.state.className}>Hi</span>
{this.state.text}
</span>
),
this.state.text
)
}
...
本文标签: javascriptHow to use IfElse in JSXStack Overflow
版权声明:本文标题:javascript - How to use If-Else in JSX - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744522134a2610518.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论