简体   繁体   English

React JSX 中的“if () {} else {}”语句?

[英]'if () {} else {}' statement in React JSX?

I am simply trying to use an if/else statement in React in some JSX, but I get a "Parsing error: Unexpected token".我只是想在一些 JSX 中的 React 中使用 if/else 语句,但我得到一个“解析错误:意外的令牌”。 The example ternary statement seems to work fine.示例三元语句似乎工作正常。 Can you not use if/else statements in JSX?你不能在 JSX 中使用 if/else 语句吗?

  ./src/App.js
  Line 288:  Parsing error: Unexpected token

  286 |                   { this.getInvitesForEvent(dat.id, 
  this.invitesForEventData) }
  287 |                   { true === 1 ? 'empty set' : 'has results' }
> 288 |                   { if (true) { true } else { false } }
  |                         ^
  289 |                 </div>
  290 |               ))
  291 |           }

You can't do that inside the jsx, because only expressions can be put in jsx, not statements.你不能在 jsx 中这样做,因为只有表达式可以放在 jsx 中,而不是语句。 If a ternary expression is inconvenient or illegible, you could consider doing an if statement outside the jsx如果三元表达式不方便或难以辨认,您可以考虑在 jsx 之外执行 if 语句

let val;
if (/*whatever*/) {
  val = true;
else {
  val = false;
}

return (
  <div>
    {val}
  </div>
)

As for why there's this limitation, it might help to remember what the jsx gets transpiled into.至于为什么会有这个限制,记住 jsx 被转译成什么可能会有所帮助。 Doing <div>Hello</div> turns into React.createElement("div", null, "Hello");执行<div>Hello</div>变成React.createElement("div", null, "Hello"); , and doing <div>{true? 'true': 'false'}</div> ,并做<div>{true? 'true': 'false'}</div> <div>{true? 'true': 'false'}</div> turns into React.createElement("div", null, true? 'true': 'false'); <div>{true? 'true': 'false'}</div>变成React.createElement("div", null, true? 'true': 'false');

So what would <div>{if (true) { 'true' } else { 'false ' }}</div> transpile into?那么<div>{if (true) { 'true' } else { 'false ' }}</div>会转换成什么? Something like React.createElement("div", null, if (true) { 'true' } else { 'false ' });类似React.createElement("div", null, if (true) { 'true' } else { 'false ' }); , but it's illegal to put an if statement in the middle of that code. ,但是在该代码中间放置 if 语句是非法的。 So it's also illegal to put it in the middle of the jsx.所以放在jsx中间也是违法的。

to use if/else in jsx, you can do {condition?要在 jsx 中使用 if/else,您可以执行 {condition? results: results if condition isn't met} for example if you wanted to render the home page if someone was logged in but the login page if they weren't, you would do: results: results if condition is not met} 例如,如果您想在有人登录时呈现主页,但如果他们没有登录则呈现登录页面,您可以这样做:

{ loggedIn ? <Home /> : <Login /> }

the "condition/variable?" “条件/变量?” acts as a "if condition/variable" and the ":" acts as an else.充当“if 条件/变量”,“:”充当 else。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM