[英]Separate Navigation in React Native Navigation
我目前正在弄清楚如何将自己的类中声明的导航重用于多个屏幕,或者以其他方式使用它:如果我的方法不够聪明,那么有没有更好的办法来创建导航,在多个屏幕上重复使用?
每当我尝试单击导航中的按钮时,都会收到错误消息“未定义不是对象(评估_this2.props.navigation.navigate)。因此,我想我在导航中缺少有关this.props的信息。 JS。
我之所以使用react-navigation,是因为它已在SO上和react-native文档中被推荐为可行之路。
App.js
import React from 'react';
import {createStackNavigator} from 'react-navigation';
import HomeScreen from './screens/home/HomeScreen'
import ProfileScreen from './screens/profile/ProfileScreen'
import SettingsScreen from './screens/settings/SettingsScreen'
const RootStack = createStackNavigator(
{
Home: HomeScreen,
Profile: ProfileScreen,
Settings: SettingsScreen,
},
{
initialRouteName: 'Home',
}
);
export default class App extends React.Component {
render() {
return <RootStack />;
}
}
Navigation.js-包含所有屏幕的计划导航
import React from 'react';
import {StyleSheet, View, TouchableOpacity, Text} from 'react-native';
class Navigation extends React.Component {
render() {
return (
<View style={navigationStyles.footerWrapper}>
<View style={navigationStyles.footer}>
<TouchableOpacity style={navigationStyles.footerItem}
onPress={() => this.props.navigation.navigate('Home')}>
<Text style={navigationStyles.placeholderIcon}/>
</TouchableOpacity>
<TouchableOpacity style={navigationStyles.footerItem}
onPress={() => this.props.navigation.navigate('Profile')}>
<Text style={navigationStyles.placeholderIcon}/>
</TouchableOpacity>
<TouchableOpacity style={navigationStyles.footerItem}
onPress={() => this.props.navigation.navigate('Settings')}>
<Text style={navigationStyles.placeholderIcon}/>
</TouchableOpacity>
</View>
</View>
);
}
}
const navigationStyles = StyleSheet.create({
//
});
module.exports = Navigation;
HomeScreen.js-应该包含导航但在触发onPress事件时显示错误的屏幕
import React from 'react';
import {StyleSheet, View, TouchableOpacity, Text} from 'react-native';
import styles from '../../common/customStyleSheet'
import Navigation from '../../components/navigation/Navigation';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Home',
header: null,
};
render() {
const {navigate} = this.props.navigation;
return (
<View style={styles.container}>
<Text style={homeScreenStyles.paddingMedium}>HomeScreen.</Text>
<Navigation/>
</View>
);
}
}
const homeScreenStyles = StyleSheet.create({
paddingMedium: {
paddingTop: 200,
},
});
module.exports = HomeScreen;
您的Navigation
组件不会自动从HomeScreen
继承navigation
道具,因为它只是一个子组件(它没有像HomeScreen
一样在堆栈导航器中定义)。 因此,您需要将导航作为道具传递给HomeScreen JSX中的Navigation
组件。
// HomeScreen.js
render() {
return (
<View style={styles.container}>
<Text style={homeScreenStyles.paddingMedium}>HomeScreen.</Text>
<Navigation navigation={this.props.navigation}/>
</View>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.