Why do semicolons throw error in react JSX?

南楼画角 提交于 2020-01-13 10:09:27

问题


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>

回答1:


It's because JSX {} expressions are limited to a single expression.

<div>{2 + 2; 3 + 3}</div>

..will throw an error.

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>

Which will display <div>20</div>

You might not need semi-colons anywhere.



来源:https://stackoverflow.com/questions/38885338/why-do-semicolons-throw-error-in-react-jsx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!