什么是…在这个React(使用JSX)代码中做什么,它被称为什么?
<Modal {...this.props} title='Modal heading' animation={false}>
什么是…在这个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]
其他回答
这些被称为价差。顾名思义,它的意思是把它的值放到那些数组或对象中。
如:
let a = [1, 2, 3];
let b = [...a, 4, 5, 6];
console.log(b);
> [1, 2, 3, 4, 5, 6]
... 被称为扩展属性,顾名思义,它允许表达式展开。
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} />
简而言之,我们可以说这是一条简洁的捷径。
对于那些想要简单快速理解这个问题的人:
首先,这不仅仅是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语法时,它将标签的属性作为对象属性,与给定的对象用户合并(如果存在则替换)。此外,您可能已经注意到,它只替换属性之前,而不是属性之后。所以在这个例子中,年龄保持不变。
它被称为JavaScript中的扩展语法。
它在JavaScript中用于解构数组或对象。
例子:
const objA = { a: 1, b: 2, c: 3 }
const objB = { ...objA, d: 1 }
/* Result of objB will be { a: 1, b: 2, c: 3, d: 1 } */
console.log(objB)
const objC = { ....objA, a: 3 }
/* result of objC will be { a: 3, b: 2, c: 3, d: 1 } */
console.log(objC)
你可以用JavaScript中的Object.assign()函数得到相同的结果。
参考:扩展语法
... 3个点代表JS中的展开运算符。
没有展开运算符。
let a = ['one','one','two','two'];
let unq = [new Set(a)];
console.log(a);
console.log(unq);
输出:
(4) ['one', 'one', 'two', 'two']
[Set(2)]
带有展开运算符。
let a = ['one','one','two','two'];
let unq = [...new Set(a)];
console.log(a);
console.log(unq);
输出:
(4) ['one', 'one', 'two', 'two']
(2) ['one', 'two']