gpt4 book ai didi

javascript - React Native 中未定义不是对象 '_this3.props.navigation()' 错误

转载 作者:行者123 更新时间:2023-12-03 00:12:24 31 4
gpt4 key购买 nike

运行我的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

路由.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')”

请给出解决方案

最佳答案

来自React Navigation Docs :

The binding of this in navigationOptions is not the HomeScreen instance, so you can't call setState or any instance methods on it. This is pretty important because it's extremely common to want the buttons in your header to interact with the screen that the header belongs to.

因此,正如您所看到的,在本例中,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 引用。从那里您可以成功导航

关于javascript - React Native 中未定义不是对象 '_this3.props.navigation()' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54671142/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com