ReactJS 文档说了一些有趣且强大的关于他们的 JSX 的能力:
You can embed any JavaScript expression in JSX by wrapping it in curly braces. For example,
2 + 2
,user.firstName
, andformatName(user)
are all valid expressions.
https://reactjs.org/docs/introducing-jsx.html#embedding-expressions-in-jsx
这对我来说是如此强大和有趣,因为这在 AngularJS 和 EmberJS 中是不可能的。 Angular 在其标记中使用 Angular 表达式,而 EmberJS 在其标记中使用 Handlebar 表达式。
Q1)ReactJS 如何实现读取 JSX 中的任何 JS 表达式?
Q2) 他们是否在幕后使用 eval()?
最佳答案
JSX 是 a Babel plugin它会提前转换您的源代码,而不是在运行时。
理解这一点可以让我们明白为什么 Yuri's answer is correct ,以及 JSX 如何计算任意表达式。
作为短前缀,Babel是一个常用的 Javascript 编译器,根据您的配置,它允许您做一些有用的事情。一个非常常见的示例是转译 ES6 功能,以便代码可以在 ES5 环境中使用:
代码在:
[1, 2, 3].map(n => n * 2);
代码输出:
[1, 2, 3].map(function (n) {
return n * 2;
});
JSX Babel 插件做了类似的事情,它将易于阅读的 JSX 语法转换为 React 函数调用(如果您不将其与 React 一起使用,则为其他类似的东西)。
From their own demo ,代码在:
var profile = <div>
<img src="avatar.png" className="profile" />
<h3>{[user.firstName, user.lastName].join(' ')}</h3>
</div>;
代码输出:
var profile = React.createElement("div", null,
React.createElement("img", { src: "avatar.png", className: "profile" }),
React.createElement("h3", null, [user.firstName, user.lastName].join(" "))
);
理解了这一点,现在很容易看出 1) 可以使用任何表达式,因为根本不对表达式求值;和 2) eval
根本不需要——代码提前转换。
关于javascript - ReactJS 如何评估 JSX 中的任何 JavaScript 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48700782/