在入口初始化
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
import React, { Component } from 'react';
import { Image } from 'react-native';
import Home from './app/home/Home'
import App from './App'
import Profile from './app/home/Profile'
import Detail from './app/detail/Detail'
import { createStackNavigator, createAppContainer } from 'react-navigation';
const MainNavigator = createStackNavigator({
Home: Home,
App: App,
Profile: Profile,
Detail: Detail,
},
{
initialRouteName: "App"
});
const AppContainer = createAppContainer(MainNavigator);
AppRegistry.registerComponent('MyReactNativeApp', () => AppContainer);
路由是全局的初始化一次即可,然后进行页面跳转
export default class home extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Go to Details"
onPress={() => this._navigateToScreen("Detail")}
/>
</View>
</View>
)
}
_navigateToScreen(screen) {
const {navigate} = this.props.navigation;
navigate(screen);
}
}
这时候报错: undefined is not an object (evaluating 'this.props.navigation.navigate')
原因是在一个页面组件中调用了另一个组件,而跳转动作在被调用组件中定义。则会出现当前呈现页面的this与跳转动作发生的this不一致,导致跳转动作不能被调用。
解决办法:在当前呈现页面传入navigation
import React, { Component } from "react";
import { Image, FlatList, StyleSheet, Text, View } from "react-native";
import TabNavigator from 'react-native-tab-navigator';
import Home from './app/home/Home'
import Profile from './app/home/Profile'
const HOME = require('./app/img/home.png');
const HOME_P = require('./app/img/home_p.png');
const MINE = require('./app/img/mine.png');
const MINE_P = require('./app/img/mine_p.png');
export default class SampleAppMovies extends Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 'home'
}
}
render() {
return (
<TabNavigator>
<TabNavigator.Item
selected={this.state.selectedTab === 'home'}
title="Home"
renderIcon={() => <Image source={HOME} style={{width:20,height:20}}/>}
renderSelectedIcon={() => <Image source={HOME_P} style={{width:20,height:20}}/>}
// badgeText="1"
onPress={() => this.setState({ selectedTab: 'home' })}>
{/* {homeView} */}
//传入navigation******************************************************
<Home navigation={this.props.navigation} />
</TabNavigator.Item>
<TabNavigator.Item
selected={this.state.selectedTab === 'profile'}
title="Profile"
renderIcon={() => <Image source={MINE}style={{width:20,height:20}}/>}
renderSelectedIcon={() => <Image source={MINE_P}style={{width:20,height:20}}/>}
// renderBadge={() => <CustomBadgeView />}
onPress={() => this.setState({ selectedTab: 'profile' })}>
{/* {profileView} */}
//传入navigation******************************************************
<Profile navigation={this.props.navigation} />
</TabNavigator.Item>
</TabNavigator>
);
}
}

在使用ReactNative开发时,遇到一个常见的错误:'undefined is not an object (evaluating 'this.props.navigation.navigate')'。问题源于在一个组件中调用另一个组件,而导航操作在被调用组件中定义,导致当前组件的this与导航对象不一致。解决方法是在调用组件时将navigation对象传递给被调用组件。
1051

被折叠的 条评论
为什么被折叠?



