我的情况是,我有 Navigation 组件,它是基础组件,正在监听 Navigations
状态(Redux)。它应该扩展到 HorizontalNavigation 和 VerticalNavigation,以便将来轻松重用代码。
我的问题是,现在我已经有了 Navigation.jsx 的“最终”版本,我可以将它作为一个类进行扩展,但不能覆盖它的方法。它触发 super(Navigation) 方法,而不是 final方法。我需要重写水平或垂直组件中的方法。
控制台上没有代码错误,所以这不是破坏性的事情,但我不知道如何处理如何扩展它。
Navigation.jsx
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { itemAction, stageAction } from 'Store/Actions/Actions';
class Navigation extends Component {
// ACTIONS
leftAction () {
this.onLeftAction();
}
onLeftAction () {}
rightAction () {
this.onRightAction();
}
onRightAction () {}
downAction () {
this.onDownAction();
}
onDownAction () {}
upAction () {
this.onUpAction();
}
onUpAction () {}
// STAGES
nextStage (slug) {
this.goToStage(slug);
}
previousStage (slug) {
this.goToStage(slug);
}
goToStage (slug) {
// Just for illustration purpose
// let { dispatch } = this.props;
// dispatch(stageAction(slug));
}
// ITEMS
nextItem (index) {
this.goToItem(index);
}
previousItem (index) {
this.goToItem(index);
}
goToItem (index) {
// Just for illustration purpose
// let { dispatch } = this.props;
// dispatch(itemAction(index));
}
render () {
return ();
}
}
function mapStateToProps (state, props) {
navigation: state.Navigations[props.slug]
}
export default connect(mapStateToProps)(Navigation);
水平.jsx
import React from 'react';
import Navigation from 'Components/Navigation/Navigation';
class HorizontalNavigation extends Navigation {
onLeftAction (previousItemIndex) {
this.previousItem(previousItemIndex);
}
onRightAction (nextItemIndex) {
this.nextItem(nextItemIndex);
}
onTopAction (slug) {
this.previousStage(slug);
}
onDownAction (slug) {
this.nextStage(slug);
}
}
export default HorizontalNavigation;
VerticalNavigation 则相反。左右为舞台;上下移动项目。
我不想每次使用水平或垂直时都重复使用导航组件,并重写相同的逻辑一遍又一遍。
最佳答案
我正在使用高阶组件模式,导出一个函数来连接扩展组件,例如:
import { connect as reduxConnect } from 'react-redux'
...
export class Navigation extends Component{
...
export function connect(Component){
return reduxConnect(
(state, props)=>({...})
)(Component);
}
export default connect(Navigation)
在 Horizontal.jsx 中你可以这样做
import { Navigation, connect } from './Navigation';
class Horizontal extends Navigation{
...
export default connect(Horizontal);
这样,您就可以将 connect(mapStateToProps) 保留在一个位置。
关于reactjs - 如何扩展 "connected"组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42774676/