JSX Spread Attributes on client side non-ES6 browsers

前端 未结 2 1626
死守一世寂寞
死守一世寂寞 2021-01-16 15:43

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

var props = {};
props.foo = x;
props.bar = y;
var component = 

        
2条回答
  •  自闭症患者
    2021-01-16 16:38

    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 = ;
    

    ...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.

提交回复
热议问题