为什么分号在React JSX中抛出错误? [英] Why do semicolons throw error in react JSX?
问题描述
下面是我在JSX中渲染方法的一部分-为什么})
之后的分号会引发错误?在普通的JavaScript中完全没问题
Below is part of my render method in JSX - why does the semicolon after the })
throw an error? It's perfectly fine in normal JavaScript
<ul>
{
libraries.map(function (item) {
return <li>{item.name.toLowerCase()}</li>;
});
}
</ul>
推荐答案
这是因为JSX {}
表达式仅限于单个表达式.
It's because JSX {}
expressions are limited to a single expression.
<div>{2 + 2; 3 + 3}</div>
..将引发错误.
但是,您可以通过使用两个{}
表达式来解决此问题
However you can solve this by having two {}
expressions
<div>{2 + 2}{3 + 3}</div>
如果只有一个表达式,则不需要分号.
There's no need for semi-colons if there will only be a single expression.
如果您想了解所有相关信息,可以在返回最后一个用逗号分隔的表达式之前,在表达式中使用鲜为人知的逗号运算符进行一些本地工作:
If you want to get all hacky about it, you can use the lesser known comma operator in expressions to do some local work, before returning the last expression separated by commas:
let x
...
<div>{x = 20, x}</div>
哪个将显示<div>20</div>
这篇关于为什么分号在React JSX中抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!