关于ts类型声明的一些思考
当我试图将一些props的参数传递给子组件时,父组件提示我缺少了必要的参数,我才发现是因为我使用了Navigation插件,该插件会代替我隐式传递navigation、route等参数
import React from 'react'; import { NavigationContainer, TabNavigationState, RouteProp } from '@react-navigation/native' import Home from '../pages/Home'; class BottomTabs extends React.Component<IProps> { render() { return ( <NavigationContainer> <Tab.Navigator> <Tab.Screen name="Home" component={Home} options={{tabBarLabel: '首页', headerTitle: '首页'}}></Tab.Screen> <Tab.Screen name="Account" component={Account} options={{tabBarLabel: '账号'}}></Tab.Screen> </Tab.Navigator> </NavigationContainer> ); } } export default BottomTabs;
因此我必须在子组件的IProps声明中使用“?.”表明navigation、route这两个参数不是必须的
import { createStackNavigator, StackNavigationProp } from '@react-navigation/stack'; type RootStackNavigation = StackNavigationProp<RootStackParamList> interface IProps { navigation?: RootStackNavigation; route?: Route; } class Home extends React.Component<IProps> { render() { return ( <View> <Text>ddd</Text> </View> ); } } export default Home;
而因为navigation、route不是必传的,所以当我使用这两个参数时,我必须先对他们进行判空,否则ts会一直提示该值可能是undefined的,从而规避不必要的空指针异常
function getHeaderTitle(route: Route) { const routeName = route.state ? route.state.routes[route.state.index].name : route.params?.screen return routeName } class Home extends React.Component<IProps> { componentDidMount(): void { const { navigation, route } = this.props; navigation?.setOptions({ headerTitle: route ? getHeaderTitle(route) : 'xxxx' }) } render() { return ( <View> <Text>ddd</Text> </View> ); } } export default Home;