代码之家  ›  专栏  ›  技术社区  ›  me-me

解构道具,同时添加道具。-有可能吗?

  •  1
  • me-me  · 技术社区  · 6 年前

    我有一些这样的道具。

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

    差不多吧。

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

    记得 我想保留身体里的东西,但要加上鼻涕虫。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Seth McClaine    6 年前

    假设

    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;
    
        2
  •  1
  •   Roman Maksimov    6 年前

    给予 body

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

    身体 name 身体

    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);