React Navigation-无法读取未定义的属性“navigate”
2017-03-14
24311
我一直在尝试使用 react navigation ,但是当我尝试将导航项移动到它们自己的组件中时遇到了问题。
HomeScreen.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text
} from 'react-native';
import NavButton from '../components/NavButton'
class HomeScreen extends Component {
render() {
return (
<View style={styles.container}>
<Text>
Hello World
</Text>
<NavButton
navigate={this.props.navigator}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
export default HomeScreen;
然后在 NavButton 组件中,我尝试导航到新屏幕。
class NavButton extends Component {
render() {
return (
<View>
<Button
title="Go to About"
onPress={() => this.props.navigator.navigate('About')}
/>
</View>
);
}
}
export default NavButton;
但是我一直收到错误“无法读取未定义的属性‘navigate’。
这也是我的 Router.js 文件。
import React from 'react';
import {StackNavigator} from 'react-navigation';
import HomeScreen from '../screens/HomeScreen'
import AboutScreen from '../screens/AboutScreen'
export const AppNavigator = StackNavigator({
Home: {
screen: HomeScreen
},
About: {
screen: AboutScreen
}
})
3个回答
如果将
navigate={this.props.navigator
重命名为
navigator={this.props.navigation
,它应该可以工作,因为在 NavButton 中您正在调用
this.props.navigator.navigate
。
Matt Aft
2017-03-14
import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';
function GoToButton() {
const navigation = useNavigation();
return (
<Button
title='Screen Name'
onPress={() => navigation.navigate(screenName)}
/>
);
}
您可以将 @react-navigation/native 中的 useNavigation 与 React Navigation v 5.x 结合使用。 更多详细信息请参阅 文档 。
Ujith Nimantha
2021-02-24
非屏幕组件的普通组件默认不会接收导航道具。
要解决此异常,您可以在从屏幕渲染 NavButton 时将导航道具传递给它,如下所示:
<NavButton navigation={this.props.navigation} />
或者,我们可以使用
withNavigation
函数自动提供导航道具
import { withNavigation } from 'react-navigation';
class NavButton extends React.Component {
render() {
return (
<Button
title="Back"
onPress={() => {
this.props.navigation.goBack();
}}
/>
);
}
}
// withNavigation returns a component that wraps NavButton and passes in the
// navigation prop
export default withNavigation(NavButton);
参考: https://reactnavigation.org/docs/en/connecting-navigation-prop.html
anmolakhilesh
2019-10-16