我正在尝试添加一个默认属性,当我继承ReactJS和ES6中的组件类时,该属性应引用实例函数。详细地说,我有来自npm(react-day-picker)的datepicker,并希望确保始终将两个属性发送到基类:
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方法中解决它?
答案 0 :(得分:2)
Referencing my comment on another answer
你应该从继承中继续,这是一种反模式。
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 are dead。
答案 1 :(得分:0)
其中一个可能的解决方案是在父类中指定两个空函数,然后可以在子类中覆盖它们。
class BaseDayPicker extends React.Comnponent {
//...
onMouseDown() {
this.props.onMouseDown();
}
onMouseUp() {
this.props.onMouseUp();
}
//....
}
class DayPicker extends React.Comnponent {
//...
onMouseDown() {
this.isDayPickerMouseDown = true;
super.onMouseDown();
}
onMouseUp() {
this.isDayPickerMouseDown = false;
super.onMouseUp();
}
//....
}
因此,在这种情况下,您可以调用在props中传递的类方法和函数。
在您的情况下,最好将BaseDayPicker
包装到另一个扩展其功能的组件中,而不是尝试扩展组件本身。