创建项目
react-native init 项目名字 --version 0.56.0
添加 TypeScript
官方文档 [ link ]添加 React Navigation
官方文档 [ link ]
a. 安装 react-navigation
yarn add react-navigation
b. 安装 react-native-gesture-handler
yarn add react-native-gesture-handler
c. Link all native dependencies:
react-native link
如果使用TypeScript的话,需要再执行:
yarn add @types/react-navigation
创建
Games.tsx
文件,用于跳转
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class Games extends React.Component {
static navigationOptions = {
title: 'Games',
};
render() {
return (
<View style={styles.container}>
<Text>Games's Page!</Text>
<Button
title="Back to home"
onPress={() =>
this.props.navigation.navigate('Home')
}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
- 创建
Home.tsx
文件,作为主页面
import Games from '../Games/Games';
import React from "react";
import { View, Text, Button } from "react-native";
import { createStackNavigator, createAppContainer } from "react-navigation";
class Home extends React.Component {
static navigationOptions = {
title: 'Main',
};
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>This's Main Screen</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Games')}
/>
</View>
);
}
}
const AppNavigator = createStackNavigator({
Home: { screen: Home },
Games: { screen: Games },
});
export default createAppContainer(AppNavigator);
- 然后在
App.tsx/App.js
入口文件中, 引用创建好的Navigator
import React, {Component} from 'react';
import AppContainer from './components/Home/Home'
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
- 运行!
应该是没那么顺利的... 我被卡了两天.. 如果一次就成功,那恭喜你...
-
遇到的问题:
学习的过程是真的恶心...
- 解决:
把模拟器reset了,然后重新 runreact-native run-ios
参考链接:[link]