美文网首页ReactNativeReactNative系列ReactNative
ReactNative - 使用TypeScript来编写

ReactNative - 使用TypeScript来编写

作者: Cosecant | 来源:发表于2018-05-13 00:58 被阅读99次

背景

最近用Javascript编写了一个比较简单的ReactNative项目,个人在开发中始终感觉对于弱类型语言表示蛋疼,因为是弱类型语言,有时候对于一个方法的调用必须要查找函数库或者字段库,亦或者查看源代码,因此显得也有点浪费时间。因以前接触过微软的TypeScript语言,所以索性想着就用TypeScript代码来写,那应该是很不错了。通过参考网上大量博客,发现部分博客是有问题的(或许是版本问题吧),经过多次修改和验证,终于把它弄出来了!

实验环境
系统:Deepin Linux 15.5
IDE: WebStorm 2018.1.3
Node: v10.0.0

实施

话不多说,因为TypeScript可以编译生成JS文件,然后供给ReactNative调用,因此我们第一步需要创建一个ReactNative项目。

  • No.1 创建ReactNative项目

    react-native init RNDemo
    
  • No.2 对项目添加TypeScript支持

    sudo npm install typescript -g  #全局安装
    
    yarn add -D typescript  #项目根目录安装
    
    yarn add -g typings  #项目添加TypeScript类型支持
    

    根目录添加配置tsconfig.json文件

    tsc --init
    

    替换tsconfig.json文件内的内容,内容如下:

    {
      "compilerOptions": {
          "target": "es6",
          "allowJs": true,
          "jsx": "react",
          "sourceMap": false,
          "noImplicitAny": false
      },
      "exclude": [
          "node_modules"
      ]
    }
    
    tsd init #初始化项目->TypeScript
    
  • No.3 添加相应的React库到TypeScript中,不然tsx代码中将不能使用相关模块

    yarn add -D typescript
    
    yarn add -D @types/react @types/react-native @types/react-navigation
    
  • No.4 至此,这个项目已经可以配置使用TypeScript进行ReactNative开发,祝你开发愉快!

Example 示例:

  1. 文件: App.tsx
import * as React from 'react';
import {StackNavigator,} from "react-navigation";
import HomeScreen from "./src/ui/HomeScreen";
import CardStackStyleInterpolator from "./src/util/interpolator/CardStackStyleInterpolator";
import SettingsScreen from "./src/ui/SettingsScreen";

const StackRoot = StackNavigator({
    'Home': {screen: HomeScreen},
    'Settings': {screen: SettingsScreen},
}, {
    initialRouteName: 'Home',
    mode: 'card',
    transitionConfig: (() => ({
        screenInterpolator: CardStackStyleInterpolator.forHorizontal
    })),
});

export default class App extends React.Component {

    constructor(props) {
        super(props);
    }

    render(): React.ReactNode {
        return (<StackRoot/>);
    }

}
  1. 文件 HomeScreen.tsx
import * as React from 'react';
import {
    View,
    Text,
    TouchableOpacity,
} from 'react-native';
import BaseScreen from "../core/base-ui/BaseScreen";

export default class HomeScreen extends BaseScreen {

    constructor(props) {
        super(props);
    }

    render(): React.ReactNode {
        return (
            <View>
                <Text>首页</Text>
                <TouchableOpacity activeOpacity={0.7}
                                  onPress={() => this._forward('Settings')}>
                    <Text style={{
                        width: 80,
                        textAlign: 'center',
                        textAlignVertical: 'center',
                        borderRadius: 5,
                        margin: 10,
                        paddingStart: 10,
                        paddingTop: 8,
                        paddingBottom: 8,
                        paddingEnd: 10,
                        borderWidth: 1,
                        borderColor: '#2299ff'
                    }}>跳转啊!</Text>
                </TouchableOpacity>
            </View>
        );
    }

}

3.文件 Settings.tsx

import * as React from 'react';
import {
    View,
    Text,
} from "react-native";
import BaseScreen from "../core/base-ui/BaseScreen";

export default class SettingsScreen extends BaseScreen {

    render(): React.ReactNode {
        return (
            <View>
                <Text>第二页</Text>
            </View>
        );
    }

}

4.文件 BaseScreen.tsx

import * as React from 'react';
import {
    BackHandler,
} from 'react-native';
import {
    NavigationParams,
    NavigationScreenOption,
    NavigationScreenOptions,
    NavigationScreenProps,
    NavigationStackScreenOptions
} from "react-navigation";

export default class BaseScreen extends React.Component<NavigationScreenProps, any> {

    static navigationOptions: NavigationScreenOptions = {header: null};

    constructor(props) {
        super(props);
        this._backPress = this._backPress.bind(this);
    }

    _backPress(): boolean {
        this.props.navigation.goBack();
        return true;
    }

    _forward(routeName: string, params ?: NavigationParams) {
        this.props.navigation.navigate(routeName, params);
    }

    _goBack() {
        this.props.navigation.goBack();
    }

    componentDidMount(): void {
        BackHandler.addEventListener("hardwareBackPress", this._backPress)
    }

    componentWillUnmount(): void {
        BackHandler.removeEventListener("hardwareBackPress", this._backPress);
    }

}

结语

Good Luck! 通过参考网上资料,整个项目已经可以完整跑起来了,感觉TypeScript比Javascript使用起来更爽,开发更便捷了!

相关文章

网友评论

本文标题:ReactNative - 使用TypeScript来编写

本文链接:https://www.haomeiwen.com/subject/rbjkdftx.html