扩展反应组件的问题/问题

时间:2017-08-04 07:47:37

标签: javascript reactjs ecmascript-6

我在我的反应应用中使用open source scrollbar component

我已经扩展了组件,使它看起来像这样:

import PropTypes from "prop-types";
import Scrollbars from "react-custom-scrollbars";

//  This component extends react-custom-scrollbars and allows
//  the developer to force an update of the scrollbars
//  every 'X' ms.

class ForcedScrollbars extends Scrollbars {

    componentDidMount() {
        this.rerenderTimer = setInterval(() => {
            this.update();
        }, this.props.forceRerenderTimer);
    }

    componentWillUnmount() {
         clearInterval(this.rerenderTimer);

    }
}

ForcedScrollbars.propTypes = {
    forceRerenderTimer: PropTypes.number
};

export default ForcedScrollbars;

我有两个问题。

  1. 父组件componentDidMount中的Scrollbars方法如下所示:

    componentDidMount() {
       this.addListeners();
       this.update();
       this.componentDidMountUniversal();
    }
    
  2. 在我的ForcedScrollbars组件中,ForcedScrollbars componentDidMount调用会调用相同的方法,还是必须再次显式调用它们?即。

    class ForcedScrollbars extends Scrollbars {
    
        componentDidMount() {
           this.addListeners();
           this.update();
           this.componentDidMountUniversal();
           this.rerenderTimer = setInterval(() => {
              this.update();
           }, this.props.forceRerenderTimer);
        }
    
      // REST OF COMPONENT //
    
    1. 我在控制台中看到错误
    2.   

      警告:标记上的未知prop forceRerenderTimer。删除它   来自元素的道具。有关详细信息,请参阅...(Facebook链接)...

      正如您在上面的代码中所看到的,我有以下内容似乎无法正常工作。

      ForcedScrollbars.propTypes = {
          forceRerenderTimer: PropTypes.number
      };
      

      此外,我已经尝试了哪些似乎也没有效果。

      Scrollbars.propTypes = {
          forceRerenderTimer: PropTypes.number
      };
      

      点击此处codesandbox

1 个答案:

答案 0 :(得分:1)

尝试扩展Scrollbars属性类型

ForcedScrollbars.propTypes = {
   ...Scrollbars.propTypes,
   forceRerenderTimer: PropTypes.number
}

或者如果您没有使用object-rest-spread

ForcedScrollbars.propTypes = Object.assign(
   {},
   Scrollbars.propTypes,
   { forceRerenderTimer: PropTypes.number }
)

<强>更新

Scrollbars只是转储它所不知道的所有属性&#34;到指定的code根标记。因此,您添加到扩展组件的每个属性都将添加到指定的tagName

您可以在此处选择以下选项:

  1. 要求react-custom-scrollbars维护者实施更智能的道具过滤系统。假设使用propTypes购买。
  2. 通过提供省略forceRerenderTimer属性的自定义无状态组件来做一些hackery。 DemounknowProp仅用于进行健全性检查)。
  3. 代码

    class ForcedScrollbars extends Scrollbars {
        static propTypes = {
          ...Scrollbars.propTypes,
          forceRerenderTimer: PropTypes.number,
          // allow components as root
          tagName: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.func
          ])
        };
    
        static defaultProps = {
          ...Scrollbars.defaultProps,
          // omit forceRerenderTimer
          tagName: allProps => {
            const {
              forceRerenderTimer,
              ...props,
            } = allProps
    
            return createElement('div', props)
          },
        }
    
相关问题