如何用Typescript运行React Native应用程序

673 阅读5分钟

如何用Typescript运行React Native应用程序

React Native默认是在JavaScript上运行的。不过,也可以将React Native应用设置为完全在TypeScript上运行。

本教程将向读者介绍用TypeScript运行React Native应用。我们将讨论用TypeScript运行React Native应用的优势,以及如何设置它。

最后,我们将创建一个使用TypeScript的简单博客应用。

前提条件

要跟上本教程,你需要以下条件。

  • 对TypeScript、React.js和React Native有一定了解
  • 安装了GoNode.js

用TypeScript初始化你的第一个React Native项目

为了让项目运行,使用Expo CLI,这是一个支持各种使用场景的命令行工具。

第一步是下载并安装Expo CLI。继续并运行以下命令。

npm install --global expo-cli

--global 标志会在全局范围内安装Expo ,这样整个操作系统的任何项目都可以访问它。

你可以通过在终端运行下面的命令来检查Expo CLI 是否被成功安装。

expo whoami

如果Expo CLI 被正确安装,安装的版本将被登录到你的终端上。

要使用TypeScript创建我们的React Native项目,导航到你想让你的项目所在的目录,并运行以下命令。

expo init -t expo-template-blank-typescript react-native-blog-app

我们的应用程序将被引导到一个空白的TypeScript应用程序模板。现在你可以导航到项目文件夹,如下图所示。

cd react-native-blog-app

让我们安装以下软件包,以改善不同React Native屏幕之间的导航。

npm install @react-navigation/native @react-navigation/native-stack

使用Expo 安装上述软件包的同行依赖关系。

expo install react-native-screens react-native-safe-area-context

然后通过使用下面的命令运行你的项目。

npm run android # for android
npm run ios # for ios

使用设备上的Expo Go 应用程序扫描记录在终端上的QR码。该应用程序将自动加载。

default-landing-screen

使用React Native设置一个TypeScript博客应用程序

现在,一个基本的TypeScript React Native应用已经设置好了,让我们来扩展一下,创建一个方便的应用。

在本指南中,我们将使用TypeScript和React Native创建一个博客应用。

创建应用程序组件

在项目文件夹内创建一个目录,并将其命名为components 。在components 目录内,创建两个文件。

  • Posts.tsx:用于渲染多个帖子。
  • Post.tsx:用于渲染单个帖子。

添加以下代码到你的Posts.tsx

import {Text,View} from "react-native";

export default function Posts(){
    return(
        <View>
            <Text>Posts content will be here</Text>
        </View>
    )
}

将以下代码添加到你的Post.tsx

import {Text,View} from "react-native";

export default function Post(){
    return(
        <View>
            <Text>Post content will be here</Text>
        </View>
    )
}

在你的App.tsx ,导入导航包,如下所示。

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

接下来,导入两个屏幕。

import Posts from './components/Posts';
import Post from './components/Post';

创建堆栈导航器。

const Stack = createNativeStackNavigator();

我们需要返回一个包含要显示的屏幕的视图。

export default function App() {
    return (
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen name="Posts" component={Posts} options={{
                    title: 'Posts',
                }} />
                <Stack.Screen name="Post" component={Post} options={{
                    title: 'Post',
                }} />
            </Stack.Navigator>
        </NavigationContainer>
    );
}

这些屏幕在NavigationContainerStack.Navigator 内。当我们从一个屏幕导航到另一个屏幕时,应用程序将使用该特定屏幕的名称。

你的应用程序现在应该改变显示的文本,因为应用程序正在调用Posts 组件。

skeleton-posts-screen

添加帖子

这篇文章将使用存储在应用程序中的静态帖子。在项目文件夹中创建一个lib 目录。在lib 内,创建一个posts.ts 文件来存放帖子。编辑posts.ts ,如下所示。

export default [
    {
        id: 1,
        title: 'Dummy title for the first post.',
        excerpt: "Dummy excerpt for the first post.",
        content: "Dummy content here for the first post."
    },
    {
        id: 2,
        title: 'Dummy title for the second post.',
        excerpt: 'Dummy excerpt for second post.',
        content: 'Dummy content here for the second post.'
    },
    {
        id: 3,
        title: 'Dummy title for the third post',
        excerpt: 'Dummy excerpt for third post.',
        content: 'Dummy content here for the third post.'
    },
    {
        id: 4,
        title: 'Dummy title for the fourth post',
        excerpt: 'Dummy excerpt for the fourth post',
        content: 'Dummy content here for the fourth post.'
    },
    {
        id: 5,
        title: 'Dummy title for the fifth post',
        excerpt: 'Dummy excerpt for the fifth post',
        content: 'Dummy content here for the fifth post.'
    }
]

在这种情况下,我们要导出一个帖子的列表。每个帖子包含以下数据。

  • id:一个唯一的整数值。
  • title:帖子的标题。
  • excerpt:标题的小描述。
  • content:假的文章内容。

取回帖子

要获取文章,请浏览你的components/Posts.tsx 文件。首先。

导入StyleSheet 和假的帖子。

import {StyleSheet,Button} from 'react-native';
import {NavigationProp} from '@react-navigation/native';
import posts from '../lib/posts';

然后定义一个帖子的结构。

interface Post {
    id: number;
    title: string;
    excerpt: string;
    content: string;
}

定义道具的结构。

interface Props{
    navigation:NavigationProp<any>;
}

将帖子映射到视图中。

const Posts:React.FC<Props> = ({navigation}) => {
    return(
        <View>
            {
                posts.map((post:Post)=>{
                    return (
                        <View key={post.id} style={styles.postCard}> 
                            <Text style={styles.postTitle}>{post.title}</Text>
                            <Text style={styles.postExcerpt}>{post.excerpt}</Text>
                            <Button title="Read more" onPress={()=>navigation.navigate('Post',{post:item})} />
                        </View>
                    )
            })}
        </View>
    )
}

export default Posts;

每个帖子都有titleexcerpt ,和一个由其onPress 监听器处理的read more 按钮。添加CSS样式,如下所示。

const styles = StyleSheet.create({
    postCard:{
        width:'100%',
        padding:10,
    },
    postTitle:{
        fontSize:18,
        fontWeight:'bold',
    },
    postExcerpt:{
        fontSize:15,
        color:'#666',
    }
});

App.tsx ,编辑样式并删除中心对齐。

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    paddingTop: 40,
  },
});

你的帖子现在应该显示在你的屏幕上了。

posts-screen

取出一个单一的帖子

要获取一个单一的帖子,导航到components/Post.tsx 文件,并导入navigationview 工具。

import {Text,View} from "react-native";
import {NativeStackScreenProps} from '@react-navigation/native-stack';

实现一个PostItem 的接口。

interface PostItem {
    id:number;
    title:string;
    excerpt:string;
    content:string;
}

定义帖子的类型。

type Post =  {
    PostDetails:PostItem
}

定义route 的道具结构。

type Props  ={
    route: NativeStackScreenProps<Post,'PostDetails'>
}

从路由中获取帖子项目,并在视图中显示。

const Post: React.FC<Props> = ({ route }) => {
    const post: PostItem = route.params.post;
    return (
        <View>
            <Text>{post.title}</Text>
            <Text>{post.excerpt}</Text>
            <Text>{post.content}</Text>
        </View>
    )
}
export default Post;

当你点击一个帖子时,你将被重定向到一个显示该帖子内容的特定页面。

post-screen-example

结论

本教程向你介绍了TypeScript和React Native。我们创建了一个使用React Native来运行Typescript代码的应用程序。