在JSX(React)中卷曲括号是什么意思? [英] What do curly braces mean in JSX (React)?

查看:96
本文介绍了在JSX(React)中卷曲括号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个例子,要设置一个样式作出反应,您可以执行



var css = {color:red}





< h1 style = {css}> Hello世界< / h1>



为什么在第二个代码片段中需要css周围的大括号?

解决方案

花括号是一个特殊的语法,让JSX解析器知道它需要将它们之间的内容解释为JavaScript而不是字符串。 >

当您想要使用JavaScript表达式(如JSX中的变量或参考)时,您需要它们。因为如果你使用标准的双引号语法如下:



var css = {color:red} p>

< h1 style =css> Hello world< / h1>



JSX不知道您在style属性中使用变量 css 而不是字符串。通过将花括号放在变量 css 之间,您正在告诉解析器将变量的内容 css 把他们放在这里。 (在技术上它评估内容)



这个过程通常被称为插值。


For an example, to set a style in react you could do

var css = {color: red}

and

<h1 style={css}>Hello world</h1>

Why do you need the curly braces around css in the second code snippet?

解决方案

The curly braces are a special syntax to let the JSX parser know that it needs to interpret the contents in between them as JavaScript instead of a string.

You need them when you want to use a JavaScript expression like a variable or a reference inside JSX. Because if you use the standard double quote syntax like so:

var css = { color: red }

<h1 style="css">Hello world</h1>

JSX doesn't know you meant to use the variable css in the style attribute instead of the string. And by placing the curly braces around the variable css, you are telling the parser "take the contents of the variable css and put them here". (Technically its evaluating the content)

This process is generally referred to as "interpolation".

这篇关于在JSX(React)中卷曲括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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