Javascript 反应导航-无法读取属性';导航';未定义的
我一直在尝试启动并运行,但当我尝试将导航项移动到它们自己的组件中时遇到了问题 HomeScreen.jsJavascript 反应导航-无法读取属性';导航';未定义的,javascript,react-native,react-navigation,Javascript,React Native,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 { rend
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;
如果将
navigate={this.props.navigator}
重命名为navigator={this.props.navigation}
,它应该可以工作,因为在NavButton中,您调用的是this.props.navigator.navigate
一个不是屏幕组件的普通组件默认情况下不会收到导航道具
要解决此异常,可以在从屏幕渲染导航道具时将其传递到NavButton,如下所示:
或者,我们可以使用with navigation
功能自动提供导航道具
从“react navigation”导入{withNavigation};
类NavButton扩展React.Component{
render(){
返回(
{
this.props.navigation.goBack();
}}
/>
);
}
}
//withNavigation返回包裹NavButton并传入的组件
//导航道具
使用导航导出默认值(导航按钮);
请参阅:确保您正在编译ES6 如果不简单,请使用this.props.navigation 或 this.props.navigation.navigate 无论您需要什么
import*作为“React”中的React;
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 native”导入{Button};
从'@react-navigation/native'导入{useNavigation};
函数GoToButton(){
const navigation=useNavigation();
返回(
导航。导航(屏幕名称)}
/>
);
}
您可以将@react navigation/native中的useNavigation与react navigation v 5.x一起使用。
更多详细信息请参见。导航按钮上的onPress功能仍然出现错误。哦,我想应该是
this.props.navigation
而不是this.props.navigator
解决了这个问题!正确的单词是navigation={this.props.navigation}。如何使用navigator={this.props.navigation}?
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
}
})
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)}
/>
);
}