【问题标题】:How to access and extend ES7 parent class attributes at declare time in sub-class body?如何在子类主体中声明时访问和扩展 ES7 父类属性?
【发布时间】:2018-06-16 07:52:20
【问题描述】:

考虑这个类

class BasePage extends Component {
  state = {
    locale: 'en'
  };

  render() {
    return (<div>{ this.state.locale }</div>);
  }
}

如何声明一个子类,同时声明一个state 属性,该属性不会覆盖父类属性,但会扩展它?

class FooPage extends BasePage {
  state = Object.assign( ?super.state, {
    foo: 'Hello'
  });

  render() {
    return (<div>{ this.state.locale } : { this.state.foo }</div>);
  }
}

显然,super.state 不起作用,BasePage.prototype.state 也不存在。

这可能吗?

【问题讨论】:

    标签: javascript ecmascript-next


    【解决方案1】:

    我将从一个普通的 JS 角度来回答这个问题(但如果你使用 React,同样的概念也适用于 React)。

    为了让你使用 base 的 props,你需要在孩子的构造函数中这样做:

    class BasePage {
      state = {
        locale: 'en'
      }; 
    }
    
    class FooPage extends BasePage {
      constructor() {
        super();  // can't access this props without calling super first
    
        // this.state refers to super's state prop. We simply extend it using Object.assign.
        this.state = Object.assign(this.state, {
          foo: 'Hello'
        });
      }  
    
      render() {
        const { locale, foo } = this.state;
        console.log({ locale, foo });  // prints { locale: 'en', foo: 'Hello' }
      }
    }
    

    演示:https://repl.it/@mrchief/UrbanLiveTrace

    关于 React 的注意事项:由于 React 是建立在普通 JS 之上的,因此相同的概念(即首先调用 super 也适用于此)。

    或者,如果你不喜欢构造函数的方式,你可以通过getter实现类似的效果:

    class BasePage {
      get state()  {
        return { locale: 'en' }
      } 
    }
    
    class FooPage extends BasePage {
      get state()  {
        return Object.assign(super.state, {
          foo: 'Hello'
        })
      }  
    
      render() {
        const { locale, foo } = this.state;
        console.log({ locale, foo });  // prints { locale: 'en', foo: 'Hello' }
      }
    }
    

    演示:https://repl.it/@mrchief/GloriousGainsboroOpensoundsystem

    【讨论】:

    • 谢谢。我实际上最终做了第一个例子。
    猜你喜欢
    • 2015-08-25
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2017-12-09
    相关资源
    最近更新 更多