What do these three dots in React do?

2018-12-31 10:00发布

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

<Modal {...this.props} title='Modal heading' animation={false}>

16条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 10:19

That's property spread notation. It was added in ES2018, but long-supported in React projects via transpilation (as "JSX spread attributes" even though you could do it elsewhere, too, not just attributes).

{...this.props} spreads out the "own" 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

<Modal {...this.props} title='Modal heading' animation={false}>

would be the same as

<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>

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 (
      <div className={className}>
      {children}
      </div>
    );
  }
}
ReactDOM.render(
  [
    <Example className="first">
      <span>Child in first</span>
    </Example>,
    <Example className="second" children={<span>Child in second</span>} />
  ],
  document.getElementById("root")
);
.first {
  color: green;
}
.second {
  color: blue;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

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

查看更多
不流泪的眼
3楼-- · 2018-12-31 10:23

Those are called spreads. Just as the name implies. It means it's putting whatever the value of it in those array or objects.

Such as :

let a = [1, 2, 3];
let b = [...a, 4, 5, 6];
console.log(b);
> [1, 2, 3, 4, 5, 6]
查看更多
ら面具成の殇う
4楼-- · 2018-12-31 10:24

The three dots represent the Spread Operator in ES6. It allows us to do quite a few things in Javascript:

  1. Copying an array

    var shooterGames = ['Call of Duty', 'Far Cry', 'Resident Evil' ];
    var racingGames = ['Need For Speed', 'Gran Turismo', 'Burnout'];
    var games = [...shooterGames, ...racingGames];
    
    console.log(games)  // ['Call of Duty', 'Far Cry', 'Resident Evil',  'Need For Speed', 'Gran Turismo', 'Burnout']
    
  2. Destructuring an array

      var shooterGames = ['Call of Duty', 'Far Cry', 'Resident Evil' ];
      var [first, ...remaining] = shooterGames;
      console.log(first); //Call of Duty
      console.log(remaining); //['Far Cry', 'Resident Evil']
    
  3. Function arguments as array

     function fun1(...params) { 
    
     }  
    

The above is known as rest parameters and does not restrict the number of values passed to a function. However, the arguments must be of the same type.

  1. Combing two objects

    var myCrush = {
      firstname: 'Selena',
      middlename: 'Marie'
    };
    
    var lastname = 'my last name';
    
    var myWife = {
      ...myCrush,
      lastname
    }
    
    console.log(myWife); // {firstname: 'Selena',
                         //   middlename: 'Marie',
                         //   lastname: 'my last name'}
    
查看更多
浅入江南
5楼-- · 2018-12-31 10:24

... is usually called spread operator , it is use to expand where ever it is required

example

const SomeStyle = {

   margin:10,
   background:#somehexa

     }

you can use this where ever you requires it more about spread operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

查看更多
孤独寂梦人
6楼-- · 2018-12-31 10:25

As you know ... are called Spread Attributes which the name represents it allows an expression to be expanded.

var parts = ['two', 'three'];
var numbers = ['one', ...parts, 'four', 'five']; // ["one", "two", "three", "four", "five"]

And in this case(I'm gonna simplify it).

//just assume we have an object like this:
var person= {
    name: 'Alex',
    age: 35 
}

This:

<Modal {...person} title='Modal heading' animation={false} />

is equal to

<Modal name={person.name} age={person.age} title='Modal heading' animation={false} />

So in short, it's a neat short-cut, we can say.

查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 10:31

The three dots (...) are called the spread operator, and this is conceptually similar to the ES6 array spread operator, JSX taking advantage of these supported and developing standards in order to provide a cleaner syntax in JSX

Spread properties in object initializers copies own enumerable properties from a provided object onto the newly created object.

let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }

Reference:

1) https://github.com/sebmarkbage/ecmascript-rest-spread#spread-properties

2) https://facebook.github.io/react/docs/jsx-spread.html

查看更多
登录 后发表回答