简体   繁体   中英

How does es6 spread operator work on an object to props transformation?

I know in order for the {...todo} to work in the Todo component, it has to be transformed to props in something like: completed=false text="clean room" but how does the spread operator do this? Wouldn't the current {...todo} be transformed to {completed:false}, {text:"clean room"} ?

const TodoList = ({ todos, onTodoClick }) => (
  <ul>
    {todos.map(todo =>
      <Todo
        key={todo.id}
        {...todo}
        onClick={() => onTodoClick(todo.id)}
      />
    )}
  </ul>
)

The es6 spread operator indeed works by transforming {...todo} to {completed:false} , {text:"clean room"} .

However, the same operator is used in JSX but it's not necessarily the same.

From msdn docs ,

The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

Following this idea, the JSX spread operator was created. According to the React docs ,

The ... operator (or spread operator) is already supported for arrays in ES6. There is also an ECMAScript proposal for Object Rest and Spread Properties. We're taking advantage of these supported and developing standards in order to provide a cleaner syntax in JSX.

Since this already follows the idea of the spread operator, a unification of the two is indeed a welcome idea by the community

As already established, the use of the spread syntax here has nothing to do with ES6, its a JSX construct.

JSX is just syntactic sugar for a React.createElement call. The props are actually passed as an object to that function.

You can use the Babel repl to have a look how the JSX is transformed.

Without spread prop:

// In
<Component foo="bar" baz="42" />

// Out
React.createElement(
  Component,
  { foo: "bar", baz: "42" }
);

With spread prop:

// In
<Component foo="bar" {...xyz} baz="42" />

// Out
React.createElement(
  Component,
  Object.assign({ foo: "bar" }, xyz, { baz: "42" })
);

So you can see, if the props contain a spread prop, they are separated into multiple objects and simply merged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM