es6调用扩展组件功能

时间:2016-04-22 13:05:44

标签: javascript reactjs ecmascript-6

好的,我要做的是:

我正在扩展react-photo-gallery组件,它有这个openLightbox函数,我想在触发该函数时在我的组件中做其他事情,我尝试过这样的事情:

import React, { Component } from 'react';
import { FormattedMessage } from 'react-intl';
import Gallery from 'react-photo-gallery';

export class GaleryComponent extends Gallery {

  constructor(props) {
      super(props);
      this.openLightBox = this.openLightBox.bind(this);

  }
  openLightbox() {
    console.log("LIGHTBOX OPENED");
  }
}

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

import React, { Component } from 'react';
import { FormattedMessage } from 'react-intl';
import Gallery from 'react-photo-gallery';

export class GaleryComponent extends Gallery {

  constructor(props) {
    // No need to set this.openLightbox, it will be available from the prototype chain
    super(props);
  }

  // If you want to override openLightbox, you can use super and add your own code
  openLightbox() {
    super.openLightbox();
    console.log("LIGHTBOX OPENED");
  }


  // Had you not overridden it, you would be accessing the super's openLightbox
  componentDidMount() {
      this.openLightbox();
  }
}
相关问题