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

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

当前回答

对于那些想要简单快速理解这个问题的人:

首先,这不仅仅是React的语法。这是ES6中的扩展语法,它迭代(合并,添加等)数组和对象。点击这里阅读更多信息。

为了回答这个问题:

让我们想象你有这样的标签:

<UserTag name="Supun" age="66" gender="male" />

然后你这样做:

const user = {
  "name": "Joe",
  "age": "50"
  "test": "test-val"
};

<UserTag name="Supun" gender="male"  {...user} age="66" />

那么标签将等于这个:

<UserTag name="Joe" gender="male" test="test-val" age="66" />

因此,当你在React标签中使用spread语法时,它将标签的属性作为对象属性,与给定的对象用户合并(如果存在则替换)。此外,您可能已经注意到,它只替换属性之前,而不是属性之后。所以在这个例子中,年龄保持不变。

其他回答

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

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

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

这是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
<Modal {...{ title: "modal heading", animation: false, ...props} />

更加清晰。

扩展语法允许像数组和对象这样的数据结构进行解构 它们可以从中提取一个值,也可以为它们添加一个值。 如 Const obj={name:"ram",age:10 从上面的例子中,我们可以说我们解构了obj并从该对象中提取了name。 同样的, const newObj ={……obj,地址:“尼泊尔”} 从这个例子中,我们向该对象添加了一个新属性。 在数组的情况下也是类似的。

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

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

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

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

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

哪个和这个相似

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

但要干净得多。