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

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

问题描述

举个例子,你可以在 react 中设置一个样式

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

var css = {color: red}

Hello world

为什么在第二个代码片段中需要用花括号将 css 括起来?

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

推荐答案

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

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.

当您想在 JSX 中使用 JavaScript 表达式(如变量或引用)时需要它们.因为如果你像这样使用标准的双引号语法:

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 }

Hello world

JSX 不知道您打算在 style 属性中使用变量 css 而不是字符串.通过在变量 css 周围放置花括号,您是在告诉解析器获取变量 css 的内容并将它们放在这里".(技术上是评估内容)

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天全站免登陆