React Native Component不能使用super

问题描述 投票:0回答:1

我已经为React组件创建了一个具有一些函数的组件,我想在多个组件中使用它们。

我已经尝试过实现它,但每当我尝试调用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和我调用的函数都不是箭头函数。

我该如何解决这个问题? (它们是基于实例的,所以我想远离为此创建某种类型的库)

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);
javascript reactjs react-native ecmascript-6 super
1个回答
1
投票

问题是OOP继承与功能方法(Redux connect)混合在一起。 CustomRouteViewComponent模块中的Home是连接功能组件而不是原始类组件。

可以导出CustomRouteViewComponent类用于继承目的,或者可以在连接的组件上访问原始类:

class Home extends CustomRouteViewComponent.WrappedComponent {...}

这将导致问题,因为CustomRouteViewComponent已经依赖于连接道具,但它自己的mapStateToProps将不会被考虑在内,即props.settings中不会有Home

一个合适的解决方案是在这种情况下不要将OOP与函数编程混合在一起。来自CustomRouteViewComponent的行为可以通过HOC或mapStateToProps函数的组合来实现。

© www.soinside.com 2019 - 2024. All rights reserved.