What do these three dots in React do?

前端 未结 29 2606
不思量自难忘°
不思量自难忘° 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:28

    This is a new feature in ES6/Harmony. It is called the Spread Operator. It lets you either separate the constituent parts of an array/object, or take multiple items/parameters and glue them together. Here is an example:

    let array = [1,2,3]
    let array2 = [...array]
    // array2 is now filled with the items from array
    

    And with an object/keys:

    // lets pass an object as props to a react component
    let myParameters = {myKey: 5, myOtherKey: 7}
    let component = 
    // this is equal to 
    

    What's really cool is you can use it to mean "the rest of the values".

    const myFunc = (value1, value2, ...values) {
        // Some code
    }
    
    myFunc(1, 2, 3, 4, 5)
    // when myFunc is called, the rest of the variables are placed into the "values" array
    

提交回复
热议问题