在此对象解构中,“...rest”代表什么?

What does the '...rest' stand for in this object destructuring?

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

我读过:'To fix this, composite components should "consume" any prop that is intended for the composite component and not intended for the child component',在这里:

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

并给出了一个示例,说明如何使用扩展运算符从 props 中提取变量,并将剩余的 props 放入变量中。

示例代码:

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

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

这是对象 rest operator,它根据所有未显式解构的属性创建一个对象。

注意: 因为对象 rest/spread 仍然是第 3 阶段提案,需要 babel transform 才能工作。

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

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

console.log(a);

console.log(everythingElse);

相当于数组剩余运算符:

const arr = [1, 2, 3];

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

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

不要混淆剩余运算符 (...) 和展开运算符(也就是 ...):

'...' 在下面的代码中充当休息运算符:

const { layout, ...rest } = props

但在下面的代码中,'...' 充当传播运算符:

return <div {...rest} style={getHorizontalStyle()} />