未定义不是对象'_this3.props.navigation()'错误

时间:2019-02-13 13:16:48

标签: javascript typescript react-native

运行我的React应用程序会导致NavigationOptions()错误,但在render()函数中工作正常

App.js

import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
import AppNavigator from './routs.js'


class App extends Component {
   render() {
      return (
         <AppNavigator />
      )
   }
}
export default App

routs.js

import React from 'react'
import Home from './home.js'
import Phone from './phone.js'
import PhoneScreen from './phoneScreen.js'
import {createStackNavigator, createAppContainer} from 'react-navigation';


const MainNavigator = createStackNavigator({

  home: {screen: Home},
  add: {screen: Phone},
  userScreen: {screen: PhoneScreen},

});

const AppNavigator = createAppContainer(MainNavigator);

export default AppNavigator;

home.js

import React from 'react'
import { TouchableOpacity, Text, View, TouchableHighlight, StyleSheet, Button } from 'react-native';
import { Actions } from 'react-native-router-flux';
import {AsyncStorage} from 'react-native';


class Home extends React.Component {

	constructor(props) { 
		super(props); 
	}

	static navigationOptions = {
		headerTitle: 'Contacts',
		headerRight: (
			<Button
			onPress={() => this.props.navigation.navigate('add')}
			title="create new contact"
			color="#000000"
			size="20"
			/>
			),
	     };
}
export default Home;

“ undefind不是对象(正在评估'_this3.props.navigation')”

请给出解决方案

1 个答案:

答案 0 :(得分:2)

React Navigation Docs

  

navigationOptions中的此绑定不是HomeScreen   实例,因此您不能在其上调用setState或任何实例方法。   这是非常重要的,因为要   标头中的按钮可以与标头上的屏幕进行交互   属于。

因此,如您所见,在这种情况下this并不是您认为的。这是更多来自文档的详细工作示例:

 class HomeScreen extends React.Component {
  static navigationOptions = ({ navigation }) => {
    return {
      headerTitle: <LogoTitle />,
      headerRight: (
        <Button
          onPress={navigation.getParam('increaseCount')}
          title="+1"
          color="#fff"
        />
      ),
    };
  };

  componentDidMount() {
    this.props.navigation.setParams({ increaseCount: this._increaseCount });
  }

  state = {
    count: 0,
  };

  _increaseCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  /* later in the render function we display the count */
}

如您所见,将navigationOptions从对象更改为函数可让您获取navigation引用。从那里您可以成功navigate