我只是尝试在某些 JSX 中使用 React 中的 if/else 语句,但收到“解析错误:意外的标记”。示例三元语句似乎工作正常。在 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 | }
最佳答案
您不能在 jsx 中执行此操作,因为 jsx 中只能放入表达式,而不能放入语句。如果三元表达式不方便或难以辨认,您可以考虑在 jsx 之外执行 if 语句
let val;
if (/*whatever*/) {
val = true;
else {
val = false;
}
return (
<div>
{val}
</div>
)
至于为什么会有这个限制,记住 jsx 被转译成什么可能会有所帮助。做<div>Hello</div>
变成React.createElement("div", null, "Hello");
,并做<div>{true ? 'true' : 'false'}</div>
变成React.createElement("div", null, true ? 'true' : 'false');
那么 <div>{if (true) { 'true' } else { 'false ' }}</div>
会怎样?转译成?类似 React.createElement("div", null, if (true) { 'true' } else { 'false ' });
,但在该代码中间放置 if 语句是非法的。所以放在jsx中间也是非法的。
关于javascript - React JSX 中的“if () {} else {}”语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58137667/