'...rest' 在这个对象解构中代表什么? [英] What does the '...rest' stand for in this object destructuring?

查看:37
本文介绍了'...rest' 在这个对象解构中代表什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于 react 中的 unknown-prop 警告,特别是因为我正在使用 react-bootstrap 包并且在那里偶然发现了它们.

I'm reading about unknown-prop warnings in react, particularly because I'm using the react-bootstrap package and have stumbled upon them there.

我读过:'为了解决这个问题,复合组件应该消耗"任何用于复合组件而不是用于子组件的道具',在这里:

i've read that: 'To fix this, composite components should "consume" any prop that is intended for the composite component and not intended for the child component', on here:

https://gist.github.com/jimfb/d99e0678e9da715ccf64049

https://gist.github.com/jimfb/d99e0678e9da715ccf6454961ef04d1b

并举例说明了如何使用扩展运算符将变量从 props 中拉出,并将剩余的 props 放入变量中.

and an example is given for how the spread operator can be used to pull variables off props, and put the remaining props into a variable.

示例代码:

function MyDiv(props) {
  const { layout, ...rest } = props
  if (layout === 'horizontal') {
    return <div {...rest} style={getHorizontalStyle()} />
  } else {
    return <div {...rest} style={getVerticalStyle()} />
  }
}

这里是问题所在:在给出的示例中,我不明白这里代码中的...rest"代表什么.我知道'...' = 展开语法,但是'rest' 这个词是从哪里来的,它代表什么?

Here is what the PROBLEM is: In the example given, I don't understand what the '...rest' in this code here stands for. I get that the '...' = spread syntax, but where did the word 'rest' come from and what does it stand for?

推荐答案

This is object rest 运算符,它从所有未显式解构的属性创建一个对象.

This is object rest operator, it creates an object from all properties that weren't explicitly destructured.

注意:因为对象 rest/spread 仍然是第 3 阶段的提案,并且需要 babel 变换 工作.

Note: since object rest/spread is still a stage 3 proposal, and requires a babel transform to work.

const obj = { a: 1, b: 2, c: 3};

const { a, ...everythingElse } = obj;

console.log(a);

console.log(everythingElse);

相当于数组的rest运算符:

It's equivalent to array rest operator:

const arr = [1, 2, 3];

const [a, ...rest] = arr;

console.log(a);
console.log(rest);

这篇关于'...rest' 在这个对象解构中代表什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆