为什么最好的做法是用括号将分配给变量的JSX括起来? [英] Why is it best practice to surround JSX assigned to variables with parenthesis?

查看:48
本文介绍了为什么最好的做法是用括号将分配给变量的JSX括起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,x和y的输出相同.我已经看到React代码是用两种方式编写的.有区别吗?由于我看到的许多React代码示例都使用括号语法,因此我认为这是有原因的.如果是最佳实践,那么为什么最好的做法是用括号将分配给变量的JSX括起来?如果还有其他原因,那是什么?

In the example below the output is the same for both x and y. I've seen React code written both ways. Is there a difference? As many of the React code examples I see utilize the parenthesis syntax, I assume there is a reason. If it's best practice, then why is it best practice to surround JSX assigned to variables with parenthesis? If there is another reason what is it?

let x =  <div> Hello World! </div>;
let y = (<div> Hello World! </div>);

console.log(x,y);

推荐答案

为了清楚起见,通常使用括号将JSX代码包装起来……也就是说,

In general parentheses are used to wrap the JSX code for code clarity...That is,

let y = <ul>
    <li>
        Hello World!
    </li>
</ul>;

丑陋但正确

let y = 
    <ul>
        <li>
            Hello World
        </li>
    </ul>;

格式较好,但语法上不正确(编译时会出错).

is better formatted but syntactically incorrect (will give error on compilation).

因此解决方案是使用

let y = (
    <ul>
        <li>
            Hello World
        </li>
    </ul>
);

这是两全其美.

更新:第二个代码不正确的原因是

UPDATE : The reason for the second code being incorrect is Automatic Semicolon insertion. Thanks to @EricKing for pointing that out.

这篇关于为什么最好的做法是用括号将分配给变量的JSX括起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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