在添加道具的同时解构道具。 - 可能吗?

时间:2018-08-30 21:50:51

标签: reactjs ecmascript-6

我有一些这样的道具。

const {
  header,
  footer,
  name,
  body,
  title,
} = this.props;

一切正常,但是有一种方法可以按上述语法为正文分配名称,而不必稍后分配它。

类似的东西。

const {
  header,
  footer,
  name,
  body: {...name},
  title,
} = this.props;

记住,我想保留体内的东西,但要添加一些弹头。

2 个答案:

答案 0 :(得分:1)

body自定义名称:

const {
  header,
  footer,
  name,
  body: customName,
  title,
} = this.props;

console.log(customName);

要将bodyname道具组合成单个body常量:

const this.props = {
  name: { name1: 1, name2: 2 },
  body: { body1: 3, body2: 4 }
};

const {
  header,
  footer,
  name,
  body,
  title,
} = {
  ...this.props,
  body: { ...this.props.body, ...this.props.name }
};

console.log(body);

答案 1 :(得分:1)

假设

const this = {
    props: {
        header: 'header',
        footer: 'footer',
        name: 'name',
        body: 'body',
        title: 'title',
    }
};

我认为这是您想要实现的目标。...

const {
    header,
    footer,
    name,
    body,
    title,
} = {
  ...this.props,
  body: this.props.name,
  //if body is an object, and name is an object, and you want to merge the two you can do:
  /** 
   * body: { ...this.props.body, ...this.props.name }
   */
};

console.log(body); //"name"

但似乎更简单

const {
    header,
    footer,
    name,
    title,
} = this.props;

const body = this.props.name; 
// or if you are merging
/**
 * const body = { ...this.props.body, ...name };
 */

但是就您采样而言,没有,您无法在定义(或解构)对象时引用该对象中的键。

const {
  header,
  footer,
  name,
  body: {...name}, //name is not available here, but this.props.name is
  //also `body: {...name}` is the same as `body: name`
  title,
} = this.props;