What do these three dots in React do?

前端 未结 29 2661
不思量自难忘°
不思量自难忘° 2020-11-21 23:53

What does the ... do in this React (using JSX) code and what is it called?



        
29条回答
  •  無奈伤痛
    2020-11-22 00:13

    That's property spread notation. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015), but it's been supported in React projects for a long time via transpilation (as "JSX spread attributes" even though you could do it elsewhere, too, not just attributes).

    {...this.props} spreads out the "own" enumerable properties in props as discrete properties on the Modal element you're creating. For instance, if this.props contained a: 1 and b: 2, then

    
    

    would be the same as

    
    

    But it's dynamic, so whatever "own" properties are in props are included.

    Since children is an "own" property in props, spread will include it. So if the component where this appears had child elements, they'll be passed on to Modal. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting a children property in the opening tag. Example:

    class Example extends React.Component {
      render() {
        const { className, children } = this.props;
        return (
          
    {children}
    ); } } ReactDOM.render( [ Child in first , Child in second} /> ], document.getElementById("root") );
    .first {
      color: green;
    }
    .second {
      color: blue;
    }

    Spread notation is handy not only for that use case, but for creating a new object with most (or all) of the properties of an existing object — which comes up a lot when you're updating state, since you can't modify state directly:

    this.setState(prevState => {
        return {foo: {...prevState.foo, a: "updated"}};
    });
    

    That replaces this.state.foo with a new object with all the same properties as foo except the a property, which becomes "updated":

    const obj = {
      foo: {
        a: 1,
        b: 2,
        c: 3
      }
    };
    console.log("original", obj.foo);
    // Creates a NEW object and assigns it to `obj.foo`
    obj.foo = {...obj.foo, a: "updated"};
    console.log("updated", obj.foo);
    .as-console-wrapper {
      max-height: 100% !important;
    }

提交回复
热议问题