gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:08:17 25 4
gpt4 key购买 nike

当我继承 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com