Javascript React本机组件无法使用超级
我已经为React组件创建了一个组件,其中包含一些函数,我希望在多个组件中使用这些函数 我尝试过实现它,但每当我尝试调用Javascript React本机组件无法使用超级,javascript,reactjs,react-native,ecmascript-6,super,Javascript,Reactjs,React Native,Ecmascript 6,Super,我已经为React组件创建了一个组件,其中包含一些函数,我希望在多个组件中使用这些函数 我尝试过实现它,但每当我尝试调用super.updateHeader,它都会出错崩溃 ExceptionsManager.js:84 Unhandled JS Exception: TypeError: TypeError: Cannot read property 'call' of undefined 在构造函数中使用super不会产生任何问题。 尝试使用this.updateHeader访问函数会
super.updateHeader
,它都会出错崩溃
ExceptionsManager.js:84 Unhandled JS Exception: TypeError: TypeError:
Cannot read property 'call' of undefined
在构造函数中使用super
不会产生任何问题。
尝试使用this.updateHeader
访问函数会导致
Unhandled JS Exception: TypeError: TypeError: this.updateHeader is not a function
无论是updateHeader
还是我从中调用它的函数都不是箭头函数
我如何解决这个问题?(它们是基于实例的,所以我不想为此创建某种库)
超级组件:
class CustomRouteViewComponent extends Component {
updateHeader(props) {
const {settings, navigation} = props;
props.navigation.setParams({
headerTintColor: settings.theme === 'dark' ? commonColorDark.textColor : commonColor.textColor,
backgroundColor: settings.theme === 'dark' ? commonColorDark.headerStyle : commonColor.headerStyle,
});
};
}
const mapStateToProps = state => ({settings: state.settings});
export default connect(mapStateToProps)(CustomRouteViewComponent);
主屏幕
class Home extends CustomRouteViewComponent {
componentWillMount() {
this.updateHeader(this.props);
}
render() {
return (
<View><Text>Hello!</Text></View>
)
}
}
const mapStateToProps = state => ({});
export default connect(mapStateToProps)(Home);
class Home扩展了CustomRouteView组件{
组件willmount(){
this.updateHeader(this.props);
}
render(){
返回(
你好
)
}
}
常量mapStateToProps=state=>({});
导出默认连接(MapStateTops)(主);
问题在于OOP继承与函数方法混合(Reduxconnect
)<Home
模块中的code>CustomRouteViewComponent是连接的功能组件,而不是原始类组件
CustomRouteViewComponent
类可以出于继承目的导出,或者可以在连接的组件上访问原始类,如下所示:
class Home extends CustomRouteViewComponent.WrappedComponent {...}
这将导致问题,因为CustomRouteViewComponent
已经依赖于连接的道具,但它自己的MapStateTrops
将不被考虑,即Home
中不会有props.settings
在这种情况下,正确的解决方案是不要将面向对象编程与函数式编程混合使用。
CustomRouteViewComponent
的行为可以通过HOC或mapStateToProps
函数的组合来实现。你说的“创建库”是什么意思?我的意思是用各种帮助函数创建一个单独的文件我已经用super.updateHeader(这个.props)添加了两个组件的基础代码>