为什么分号在React JSX中抛出错误? [英] Why do semicolons throw error in react JSX?

查看:194
本文介绍了为什么分号在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屋!

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