在ES6中继承reactjs类时添加默认属性

石头

我试图添加一个默认属性,当我在ReactJS和ES6中继承组件类时,该属性应引用实例函数。详细地说,我有npm的datepicker(react-day-picker),并希望确保始终将两个属性发送到基类:

export default class DayPicker extends BaseDayPicker {
constructor(props) {
    var { ...newProps } = props;
    newProps.onMouseDown = this.onDayPickerMouseDown;
    newProps.onMouseUp = this.onDayPickerMouseUp;
    super(newProps);
}

componentDidMount() {
    super.componentDidMount && super.componentDidMount();
    window.addEventListener('mousedown', this.onPageClick, false);
}

componentWillUnmount() {
    super.componentWillUnmount && super.componentWillUnmount();
    window.addEventListener('mousedown', this.onPageClick, false);
}   

onPageClick = (e) => {
    if (!this.isDayPickerMouseDown) {
        this.props.onPageClick && this.props.onPageClick();
    }
};  

onDayPickerMouseDown = (e) => {
    this.isDayPickerMouseDown = true;
};

onDayPickerMouseUp = (e) => {
    this.isDayPickerMouseDown = false;
};  

render() {
    return super.render();
}

}

上面的代码的问题是我得到了'this' is not allowed before super()

我找不到解决此问题的方法。如果无法添加必须使用的默认属性this,是否可以在render方法中解决它?

布莱尔·安德森(Blair Anderson)

引用我对另一个答案的评论

你应该瘦掉来自继承,它是一个反模式。

React是为合成而设计的这意味着什么?如果您要共享某些功能,则将其放在组件中,并以不同的方式使用道具。

TL; DR您想在这种情况下使用高阶组件

例子:

BaseDayPicker = (RenderedComponent) =>  React.Component {
  // just a function that takes a component, and returns a component.
  onMouseDown() {
    this.props.onMouseDown(doSomething());
  }

  onMouseUp() {
    this.props.onMouseUp();
  }

  //...
  // notice it renders the component that came in as a parameter.
  render(){
    return (<RenderedComponent 
      onMouseUp={this.onMouseUp} 
      onMouseDown={this.onMouseDown}
    />)  // it also adds some props! super cool
  }
} 

class DayPicker extends React.Comnponent {
  //...

  onMouseDown() {
    this.isDayPickerMouseDown = true;
    this.props.onMouseDown();
  }

  onMouseUp() {
    this.isDayPickerMouseDown = false;
    this.props..onMouseUp();
  }

  //....
} 
// NOTICE, WRAPPING ONE IN ANOTHER
export BaseDayPicker(DayPicker)

如果您想知道为什么,这里是一篇博客文章,解释为什么react mixins死了

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章