I have a new React Native app that uses Typescript. I want to use class based components. At this time, I have two classes:
RouteView.tsx
export class RouteView extends React.Component {
constructor(props: any, private title: string) {
super(props);
this.params = params;
this.title = title;
}
render() {
return <div></div>;
}
}
HomeView.tsx
export class HomeView extends RouteView {
render() { return
<View style={styles.container}>
<Text>My Mobile App!</Text>
<StatusBar style="auto" />
<Button
title="View About"
onPress={() => navigation.navigate('About')}
/>
</View>;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
When I compile this, I receive an error that says:
Property ‘render’ in type ‘HomeView’ is not assignable to the same property in base type ‘RouteView’.
Why? The code looks correct to me. In HomeView, I’m trying to override the render method of the base class. What am I doing wrong?
>Solution :
NOTE
Please don’t do inheritance. There’s so much history in React at to why inheritance is the wrong way to solve problems and why composition solves all the problems from the smallest scale to the largest scale applications.
Immediate Answer
Given your snack, it just looks like your return statement is returning the JSX. It should look like this:
export class HomeView extends RouteView {
render() {
return (
<View style={styles.container}>
<Text>My Mobile App!</Text>
<StatusBar style="auto" />
<Button
title="View About"
onPress={() => navigation.navigate('About')}
/>
</View>
)
}
}
