什么是…在这个React(使用JSX)代码中做什么,它被称为什么?
<Modal {...this.props} title='Modal heading' animation={false}>
什么是…在这个React(使用JSX)代码中做什么,它被称为什么?
<Modal {...this.props} title='Modal heading' animation={false}>
当前回答
... (JavaScript中的三个点)被称为扩展语法或扩展操作符。这允许一个可迭代对象(如数组表达式或字符串)被展开,或一个对象表达式被展开。这不是React特有的。它是一个JavaScript操作符。
这里所有的答案都是有用的,但我想列出最常用的传播语法(传播操作符)的实际用例。
1. 组合数组(串联数组)
组合数组的方法有很多种,但展开操作符允许您将其放置在数组中的任何位置。如果你想组合两个数组,并将元素放置在数组中的任何位置,你可以这样做:
var arr1 = ['two', 'three'];
var arr2 = ['one', ...arr1, 'four', 'five'];
// arr2 = ["one", "two", "three", "four", "five"]
2. 复制数组
当我们想要一个数组的副本时,我们使用array .prototype.slice()方法。但是,你也可以用展开运算符做同样的事情。
var arr = [1,2,3];
var arr2 = [...arr];
// arr2 = [1,2,3]
3.调用没有应用的函数
在ES5中,要将两个数字的数组传递给doStuff()函数,你经常使用function .prototype.apply()方法,如下所示:
function doStuff (x, y, z) {}
var args = [0, 1, 2];
// Call the function, passing args
doStuff.apply(null, args);
但是,通过使用展开操作符,可以将数组传递给函数。
doStuff(...args);
4. 解构数组
你可以使用解构和rest操作符一起将信息提取到你想要的变量中:
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }
5. 函数参数作为Rest参数
ES6还有三个点(…),它表示一个rest形参,将函数的所有剩余参数收集到一个数组中。
function f(a, b, ...args) {
console.log(args);
}
f(1, 2, 3, 4, 5); // [3, 4, 5]
6. 使用数学函数
任何将spread用作实参的函数都可以被接受任意数量实参的函数使用。
let numbers = [9, 4, 7, 1];
Math.min(...numbers); // 1
7. 两个对象合并
您可以使用展开运算符来合并两个对象。这是一种简单明了的方法。
var carType = {
model: 'Toyota',
yom: '1995'
};
var carFuel = 'Petrol';
var carData = {
...carType,
carFuel
}
console.log(carData);
// {
// model: 'Toyota',
// yom: '1995',
// carFuel = 'Petrol'
// }
8. 将字符串分离为单独的字符
您可以使用展开运算符将字符串展开为单独的字符。
let chars = ['A', ...'BC', 'D'];
console.log(chars); // ["A", "B", "C", "D"]
您可以想到更多使用扩展操作符的方法。我在这里列出的是它的流行用例。
其他回答
…(展开运算符)用于React to:
提供一种简洁的方式将道具从父组件传递给子组件。例如,给定父组件中的这些道具,
this.props = {
username: "danM",
email: "dan@mail.com"
}
它们可以通过以下方式传递给孩子,
<ChildComponent {...this.props} />
哪个和这个相似
<ChildComponent username={this.props.username} email={this.props.email} />
但要干净得多。
这三个点(…)被称为展开运算符,这在概念上类似于ES6数组展开运算符JSX 利用这些支持并开发标准,以便在JSX中提供更清晰的语法
对象初始化器中的展开属性复制自己的枚举对象 属性从提供的对象转移到新创建的对象。 设n = {x, y,…z}; n;// {x: 1, y: 2, a: 3, b: 4}
引用:
传播特性 JSX深入
传播算子!由于大多数人已经优雅地回答了这个问题,我想建议一个快速使用扩散操作符的方法列表:
…spread运算符对JavaScript中许多不同的常规任务都很有用,包括:
复制数组 连接或组合数组 使用数学函数 使用数组作为参数 向列表中添加项 在React中添加状态 结合对象 将NodeList转换为数组
查看文章了解更多细节。如何使用展开运算符。我建议你习惯它。有很多很酷的方法可以使用展开运算符。
<Modal {...{ title: "modal heading", animation: false, ...props} />
更加清晰。
那三个点…不是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]