无法在 react-navigation 5 上的屏幕之间导航
2020-03-08
914
我正在用不同的方法开发 react-navigation。 问题出在我最后尝试的方法上。
我正尝试使用自定义组件(一种按钮被驱逐)从 HomeScreen 导航到 DetailScreen。 问题是:“TypeError:未定义不是对象(评估'this.prop.navigation.navigate')”
有人能帮我理解这个问题吗? (注意:我使用的是 react-navigation 5)
我给你不同的文件:
//fichier app.js
import 'react-native-gesture-handler'
import React from 'react';
import HomeScreen from './src/screens/HomeScreen'
import DetailScreen from './src/detailscreen'
import {NavigationContainer} from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Detail" component={DetailScreen} />
</Stack.Navigator>
</NavigationContainer>
)
}
文件 HomeScreen
import React from 'react';
import { View, Text, Button } from 'react-native';
import ButtonNav from './Button';
class HomeScreen extends React.Component {
render() {
console.log('Home' + this.props)
return (
<View
style={{ alignItems: 'center', justifyContent: 'center'}}>
<View
style={{height: 120, alignItems: 'center', justifyContent: 'center'}}>
<Text>Zone 1</Text>
</View>
<ButtonNav/>
</View>
)
}
}
export default HomeScreen;
按钮
//Button
import React from 'react';
import { View, Text, Button } from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
class ButtonNav extends React.Component {
render() {
console.log(this.props.navigation)
return (
<View
style={{height: 120, alignItems: 'center', justifyContent: 'center' }}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Detail')}>
<Text>Button</Text>
</TouchableOpacity>
</View>
);
}
}
export default ButtonNav;
DetailScreen
//detail
import React from 'react';
import { View, Text } from 'react-native';
class Detail extends React.Component {
render() {
console.log(this.props)
return (
<View
style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
)
}
}
export default Detail;
2个回答
您没有 Button 类内的导航属性,您可以通过这种方式传递它:
<ButtonNav
navigation={this.props.navigation} />
或者您可以通过 props 传递事件
onPress
:
<ButtonNav
onPress={() => this.props.navigation.navigate('Detail')} />
<TouchableOpacity
onPress={this.props.onPress}>
<Text>Button</Text>
</TouchableOpacity>
Lucas Z.
2020-03-10
因此在 ButtonNav 类中,该类没有 props。
将这段代码包含在你的类中。
constructor(props){ super(props); }
Mian Jawad Ahmad
2020-03-08