客户端非ES6浏览器上的JSX Spread属性 [英] JSX Spread Attributes on client side non-ES6 browsers

查看:94
本文介绍了客户端非ES6浏览器上的JSX Spread属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ReactJS JSX有一个方法可以轻松地向组件添加大量属性:

ReactJS JSX has a method for easily adding lots of properties to a component:

var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;

这些称为Spread属性。

These are called Spread Attributes.

https://facebook.github.io/react/docs/jsx-spread.html#spread-attributes

。 .. 表示法称为ES6中使用的Spread运算符。如果您使用Babel等在服务器端渲染所有内容,这很容易使用,但是如果您想在客户端的浏览器中创建和呈现组件,那么如何在没有浏览器的情况下使用Spread Attributes支持ES6 ... Spread运算符?

The ... notation is called a Spread operator that it used in ES6. This is easy to use if you are rendering out everything on the server side using Babel, etc, but if you are wanting to create and render Components in the browser on the client side, how do you use Spread Attributes for browsers that don't support the ES6 ... Spread operator?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/ Spread_operator#Browser_compatibility

推荐答案

尽管语法类似,但JSX传播运算符与ES6传播运算符不同,使用前者不需要后者。虽然JSX转换器可以将带有JSX扩展运算符的JSX标记转换为使用ES6扩展运算符的JavaScript,但实际上它们只是将其转换为ES5代码。要了解Babel是如何做到的,在Babel网站上试用。从本质上讲,这是:

Despite the similar syntax, the JSX spread operator is not the same as the ES6 spread operator, and using the former does not require the latter. While a JSX transpiler could turn a JSX tag with a JSX spread operator into JavaScript that uses an ES6 spread operator, in practice they just turn it into ES5 code. To see how Babel does it, try it out on the Babel site. In essence, this:

var obj = { className: 'foo' };
var el = <Component id='bar' {...obj}/>;

...变为:

var obj = { className: 'foo' };
var el = React.createElement(Component,
           Object.assign({ id: 'bar' }, obj));

(根据属性的位置略有不同。)

(With slight variations depending on the positions of the attributes.)

不需要ES6传播运算符。

No ES6 spread operator needed.

换句话说,如果您使用转换器将JSX转换为JavaScript,那么,因为没有浏览器直接支持JSX - 你不需要担心具有扩展运算符的转换代码,因为你没有使用ES6扩展运算符,你使用的是JSX扩展运算符,并且它被转换成浏览器理解的东西。

In other words, if you're using a transpiler to turn your JSX into JavaScript—and you are, since no browser supports JSX directly—you don't need to worry about the transpiled code having a spread operator, because you weren't using an ES6 spread operator, you were using a JSX spread operator, and that gets transpiled into something browsers understand.

这篇关于客户端非ES6浏览器上的JSX Spread属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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