[英]React Native Component cannot use super
我已經創建了一個組件,其中包含一些我想在多個組件中使用的React組件的功能。
我已經嘗試實現它,但是每當我嘗試調用super.updateHeader
,它就會因錯誤而崩潰
ExceptionsManager.js:84 Unhandled JS Exception: TypeError: TypeError:
Cannot read property 'call' of undefined
在構造函數中使用super
可以正常工作。 嘗試使用this.updateHeader
達到功能this.updateHeader
導致
Unhandled JS Exception: TypeError: TypeError: this.updateHeader is not a function
updateHeader
或我從中調用的函數都不是箭頭函數。
我該如何解決? (它們是基於實例的,因此我想避免為此創建某種庫)
SuperComponent:
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);
問題是OOP繼承與功能方法(Redux connect
)混合在一起。 Home
模塊中的CustomRouteViewComponent
是連接的功能組件,而不是原始的類組件。
可以出於繼承目的導出CustomRouteViewComponent
類,或者可以在連接的組件上通過以下方式訪問原始類:
class Home extends CustomRouteViewComponent.WrappedComponent {...}
這將導致問題,因為CustomRouteViewComponent
已經依賴於連接的道具,但是不會考慮其自身的mapStateToProps
,即Home
中將沒有props.settings
。
在這種情況下,正確的解決方案是不要將OOP與功能編程結合使用。 CustomRouteViewComponent
的行為可以通過HOC或mapStateToProps
函數的組合來實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.