您当前的位置: 首页 >  typescript

ITKEY_

暂无认证

  • 0浏览

    0关注

    732博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

React Navigation中使用typescript简洁演示代码

ITKEY_ 发布时间:2021-11-23 16:35:33 ,浏览量:0

最近在尝试转到typescript,之前代码中含有的大量{navigaiton}:any近期打算把这样的代码优化一下。

参考以下文档: https://reactnavigation.org/docs/typescript

尽量让代码精简,形成了以下代码。希望对大家有用。

依赖
yarn add @react-navigation/native
yarn add react-native-screens react-native-safe-area-context
yarn add @react-navigation/native-stack
yarn add @react-navigation/bottom-tabs
演示代码

把以下代码保存成App.tsx就可以看到效果了。

import * as React from 'react';
import {Button, View, Text, StyleSheet} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {NativeStackScreenProps} from '@react-navigation/native-stack';
import {BottomTabScreenProps} from '@react-navigation/bottom-tabs';
import {CompositeScreenProps} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
//------------types----------------start
//Stack 所有的Screen名称
export type RootStackParamList = {
  TabNav: undefined;
  Details: undefined;
};

//我的理解就是上面的RootStackParamList的一个Copy
export type RootStackScreenProps =
  NativeStackScreenProps;

//Tab中所有的Screen 的名称
export type RootTabParamList = {
  Home: undefined;
  Settings: undefined;
};

//合并Stack 和 Tab中的所有Screen
export type RootTabScreenProps =
  CompositeScreenProps;
//------------types----------------end
//------------screens--------------start
function HomeScreen({navigation}: RootTabScreenProps) {
  return (
    
      我是首页20211123!
       navigation.navigate('Settings')}
      />
       navigation.navigate('Details')}
      />
    
  );
}

function DetailsScreen({navigation}: RootStackScreenProps) {
  return (
    
      详情页面
       navigation.push('Details')} />
    
  );
}

function SettingsScreen({navigation}: RootTabScreenProps) {
  return (
    
      设置页面
       navigation.navigate('Home')} />
       navigation.navigate('Details')}
      />
    
  );
}

//tabs
const Tab = createBottomTabNavigator();
function TabNav() {
  return (
    
      
      
    
  );
}
//------------screens--------------end
const Stack = createNativeStackNavigator();

function App() {
  return (
    
      
        
        
      
    
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
export default App;

关注
打赏
1665243900
查看更多评论
立即登录/注册

微信扫码登录

0.0421s