JSX Spread Attributes on client side non-ES6 browsers

穿精又带淫゛_ 提交于 2019-12-04 02:00:12

问题


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} />;

These are called Spread Attributes.

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

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


回答1:


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}/>;

...becomes this:

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

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

No ES6 spread operator needed.

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.




回答2:


The usual workflow of ReactJS would be transforming the JSX via Babel (by a build tool like Browserify/Webpack) before serving it to the client. Hence you get all the ES6 (or ESNext) goodies.

Getting Started | React



来源:https://stackoverflow.com/questions/33748509/jsx-spread-attributes-on-client-side-non-es6-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!