undefined不是对象(评估'_this2.props.navigation.navigate')

时间:2017-05-17 09:16:19

标签: react-native react-navigation

点击标题后,我希望它导航到下一页。但是,我不知道如何访问课外的导航道具。有关如何做到这一点的任何建议吗?

import React,{Component} from 'react'
import { View, Text, TouchableOpacity, FlatList} from 'react-native'

class header extends Component {
  render(){
    return(
        <TouchableOpacity
          onPress={() => **this.props.navigation.navigate('PageTwo')**}
        >
          <Text>{'Go to next Page Two'}</Text>
        </TouchableOpacity>
    )
  }
}

export default class PageOne extends Component {
  static navigationOptions = {
    title: 'Page One',
  }
  constructor(props) {
    super(props);
    this.state = {
      data: // ...
    };
  }

  _renderItem = ({item}) => (
    // ...
  );

  render(){
    return(
        <FlatList
          ListHeaderComponent={header}
          data={this.state.data}
          renderItem={this._renderItem}
        />
    )
  }
}

3 个答案:

答案 0 :(得分:2)

用于React Navigation 首先确保在项目中安装了react-navigation lib。 如果没有,则在cmd中运行“npm install --save react-navigation”。 然后创建一个App.js文件来保存所有路由器名称,如

App.js:

import React from 'react';
import {
  View,
  Text,
  StyleSheet,
} from 'react-native';
import {StackNavigator} from 'react-navigation';

import Splash from './src/components/Splash/Splash'
import Login from './src/components/Splash/Login'

const Navigation = StackNavigator({
  Splash : {
    screen : Splash
  },
  Login : {
    screen : Login
  },
})
export default Navigation;

在我的情况下,src是存储所有js文件的脏东西。

现在在index.android.js中设置AppRegistry.registerComponent。

<强> index.android.js

import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  View
} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Splash from './src/components/Splash/Splash'
import Navigation from './App'
export class FirstReactDemo extends Component {
  render() {
    return (
      <Splash/>
    );
  }
}
AppRegistry.registerComponent('FirstReactDemo', () => Navigation);

现在,在第一个屏幕中设置onclick侦听器。

<强> Splash.js

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

export default class SplashScreen extends Component {



static navigationOptions = {
      title: 'Splash',
    };
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <Text
          onPress={() =>navigate('Login')}
          style={styles.text}>My Splash screen</Text>
      </View>
    );
  }
}

为下一个屏幕创建Login.js文件。

答案 1 :(得分:1)

答案 2 :(得分:0)

在使用您的子组件时自己传递navigation = {navigation}