React Native组件不能使用超级

时间:2019-01-07 13:11:49

标签: 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实现该功能会导致

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);

1 个答案:

答案 0 :(得分:1)

The problem is that OOP inheritance is mixed with functional approach (Redux connect). CustomRouteViewComponent in Home module is connected functional component and not original class component.

CustomRouteViewComponent class could be exported for inheritance purposes, or original class could be reached on connected component as:

class Home extends CustomRouteViewComponent.WrappedComponent {...}

This will result in problems because CustomRouteViewComponent already relies on connected props, but its own mapStateToProps won't be taken into account, i.e. there won't be props.settings in Home.

A proper solution is to not mix OOP with functional programming in this case. The behaviour from CustomRouteViewComponent could be achieved via HOC or the composition of mapStateToProps functions.