美文网首页
react-navigation的使用

react-navigation的使用

作者: 暖羊羊_d603 | 来源:发表于2018-12-26 14:27 被阅读0次

创建了一个新的工程,并且可以运行起来,也能展示基本出helloword了,就想着 用一下导航, 本以为很简单 ,结果一运行就报错 ,记录一下过程

在当前目录操作:

  1. 需要添加库:
yarn add react-navigation 
  1. 添加完1后 运行会报错 undefined is not an object (evaluating ‘RNGeatureHandlerModule.State’) 因为还需要添加下面的库
yarn add react-native-gesture-handler
  1. (链接原生库)
react-native link

最后就是编写代码了
App.js

import React,{ Component } from 'react';
import {createStackNavigator,createAppContainer} from 'react-navigation';
import HomeScreen from "./HomeScreen";
import DetailsScreen from "./DetailsScreen";

const RootStack = createStackNavigator({
    Home: {
        screen: HomeScreen
    },
    Details: {
        screen: DetailsScreen
    }
})
const App = createAppContainer(RootStack);

export default App;

HomeScreen.js

import React, { Component } from 'react';
import {View,StyleSheet,Text,Button} from 'react-native';
import {createStackNavigator,createAppContainer} from 'react-navigation';


export default class HomeScreen extends Component{

    static navigationOptions = {
        title:'Home', //设置导航条标题
    };

    render(){
        const navigate = this.props.navigation;
        return (
            <View style={{flex:1, alignItems: 'center',justifyContent: 'center'}}>
                <Text>HomeScreen</Text>
                <Button
                    title="Go to Details"
                    onPress={() => navigate.navigate('Details')}
                />
            </View>
        );
    }

}

DetailsScreen.js

import React, { Component } from 'react';
import {View,Text,Button} from 'react-native';
import {createStackNavigator,createAppContainer} from 'react-navigation';

export default class DetailsScreen extends Component{

    static navigationOptions = {
        title:'Details', //设置导航条标题
    };

    render(){
        const navigate = this.props.navigation;
        return (
            <View style={{flex:1, alignItems: 'center',justifyContent: 'center'}}>
                <Text>Details Screen</Text>
                <Button
                    title="Go to Details"
                    onPress={() => navigate.push('Details')}
                />
                <Button
                    title="Go to Home"
                    onPress={() => navigate.navigate('Home')}
                    // 跳转到导航中定义的路由 ,当前的路由 如果已经存在 则会跳转到,不存在 则什么都不发生 否则 本例子中相当于pop
                />
                <Button
                    title="Go Back"
                    onPress={() => navigate.goBack()}
                />
            </View>
        );
    }
    
}

相关文章

网友评论

      本文标题:react-navigation的使用

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