javascript - ES6继承reactjs类时添加默认属性

标签 javascript reactjs ecmascript-6

当我继承 ReactJS 和 ES6 中的组件类时,我试图添加一个应该引用实例函数的默认属性。详细地说,我有来自 npm (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方法中解决?

最佳答案

Referencing my comment on another answer

您应该远离继承,它是一种反模式。

React 专为组合 而设计。 那是什么意思?如果您有一些功能要共享,那么将它放在一个组件中并使其以不同的方式使用 Prop 。

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 are dead .

关于javascript - ES6继承reactjs类时添加默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36678317/

相关文章:

reactjs - 为什么内联样式 style={{maxHeight :'443 px' , maxWidth : '443 px' }} is not working in component

javascript - Nodejs 异步循环正在阻止 React UI 渲染

javascript - 通过 ES6 Katas 工作,扩展 promise

javascript - 在 JavaScript 中按字符串属性值对对象数组进行分组?

javascript - JavaScript 新手 : not sure what function (o) means

javascript - 如何在 React Native + Redux 中使用 NavigationStateUtils 实现 Navigator.replace?

javascript - 使用 react-router v4 将 Prop 传递给子组件

javascript - 哪种外部环境可能导致接头不执行任何操作?

javascript - Nivo slider 在 Chrome 中不起作用

javascript - `_.defaults` 和 `_.extend` 之间的实际区别是什么?