首页 > 解决方案 > ES6 解构为“this”

问题描述

尝试 ES6 解构。

我在 React 类构造函数中使用此代码:

let { class, ...rest } = props;

上面的代码有效。this.class但我需要and中的变量this.rest

我有这个代码,它可以工作:

let { classes, ...rest } = props; 
this.classes = classes; 
this.rest = rest; 

我正在寻找这样的东西:

{ this.classes, ...this.rest } = props;  

标签: javascriptreactjsecmascript-6destructuring

解决方案


您可以使用重命名属性,但不幸的是它涉及到一些重复:

({ classes: this.classes, ...this.rest } = props);

classes是我们要离开的属性的名称propsthis.classes是分配给它的变量的名称。有了this.rest,我们显然不需要命名原始属性名称。

演示:

function Foo(props) {
    ({ classes: this.classes, ...this.rest } = props);
}

const props = {
  classes: 'some clases',
  a: 'A',
  b: 'B'
}

console.log(new Foo(props));


推荐阅读