什么是…在这个React(使用JSX)代码中做什么,它被称为什么?

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

当前回答

那三个点…不是React术语。这些是JavaScript ES6扩展操作符。这有助于在不影响原始数组的情况下创建一个新数组来执行深度复制。这也可以用于对象。

const arr1 = [1, 2, 3, 4, 5]
const arr2 = arr1 // [1, 2, 3, 4, 5]
/*
 This is an example of a shallow copy.
 Where the value of arr1 is copied to arr2
 But now if you apply any method to
 arr2 will affect the arr1 also.  
*/

/*
 This is an example of a deep copy. 
 Here the values of arr1 get copied but they 
 both are disconnected. Meaning if you
 apply any method to arr3 it will not
 affect the arr1.
 */
 const arr3 = [...arr1] // [1, 2, 3, 4, 5]

其他回答

这是ES6的一个特性,在React中也使用了这个特性。请看下面的例子:

function Sum(x, y, z) {
   return x + y + z;
}
console.log(Sum(1, 2, 3)); // 6

如果我们最多有三个参数,这种方式很好。但是,如果我们需要添加,例如,110个参数。我们是否应该定义它们并逐个添加它们?

当然,有一种更简单的方法,叫做扩散。 而不是传递所有这些参数,你写:

function (...numbers){} 

我们不知道有多少参数,但我们知道有很多。

基于ES6,我们可以重写上面的函数如下所示,并使用它们之间的扩展和映射,使其变得简单如一块蛋糕:

let Sum = (...numbers) => {
    return numbers.reduce((prev, current) => prev + current);
}
console.log(Sum(1, 2, 3, 4, 5, 6, 7, 8, 9)); // 45

…(展开运算符)用于React to:

提供一种简洁的方式将道具从父组件传递给子组件。例如,给定父组件中的这些道具,

this.props = {
  username: "danM",
  email: "dan@mail.com"
}

它们可以通过以下方式传递给孩子,

<ChildComponent {...this.props} />

哪个和这个相似

<ChildComponent username={this.props.username} email={this.props.email} />

但要干净得多。

Spread操作符允许您将可迭代对象(如对象、字符串或数组)展开为其元素,而Rest操作符则相反,将一组元素缩减为一个数组。

... 被称为扩展属性,顾名思义,它允许表达式展开。

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

在这种情况下(我要化简它)

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

这样的:

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

等于

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

简而言之,我们可以说这是一条简洁的捷径。

这些被称为价差。顾名思义,它的意思是把它的值放到那些数组或对象中。

如:

let a = [1, 2, 3];
let b = [...a, 4, 5, 6];
console.log(b);
> [1, 2, 3, 4, 5, 6]