我正在使用react-navigation第三方组件,这是我的代码:
import { StackNavigator } from 'react-navigation';
// ==============
// Profile Screen
// ==============
class ProfileScreen extends React.Component {
static navigationOptions = {
title: 'Profile',
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Profile Page</Text>
<TouchableHighlight onPress={() => navigate('Detail')}>Next</TouchableHighlight>
</View>
);
}
onEditProfile(event) {
() => navigate('Detail');
}
}
// ==============
// Detail Screen
// ==============
class DetailScreen extends React.Component {
static navigationOptions = {
title: 'Detail',
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Detail Page</Text>
</View>
);
}
}
// ==============
// Routing
// ==============
const ModelStack = StackNavigator({
Profile: { screen: ProfileScreen },
Detail: { screen: DetailScreen },
});
AppRegistry.registerComponent('ModelStack', () => ModelStack);
export default ModelStack;
在<TouchableHighlight>
的onPress活动中,它有效;当我将确切的内容放在onEditProfile()
中时,如上所示,它不起作用。为什么?如何将动作放入函数中?
额外的问题:
headerBackTitle
中的navigationOptions
设置ProfileScreen
和DetailScreen
类移动到单独的JS文件中吗?更新:更新代码onPressEditProfile
:
onPressEditProfile(event) {
const { navigate } = this.props.navigation;
console.log('Clicked Edit Profile');
() => navigate('Detail');
}
上面的代码引发了以下错误:
undefined不是一个对象(评估'this.props.navigation')
误差线位于onPressEditProfile
函数的第一行。
在函数内添加此行
const { navigate } = this.props.navigation;
是的,你可以做到。您可以在单独的文件中为所有屏幕声明导航const并导出该const。然后为不同的屏幕制作不同的文件并导航到这些屏幕。
更新的代码
import { StackNavigator } from 'react-navigation';
import React,{Component} from 'react';
import {
Text,
View,
TouchableHighlight,
} from 'react-native';
// ==============
// Profile Screen
// ==============
class ProfileScreen extends Component {
static navigationOptions = {
title: 'Profile',
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Profile Page</Text>
<TouchableHighlight onPress={() => this.onEditProfile()}><Text>Next</Text></TouchableHighlight>
</View>
);
}
onEditProfile() {
const { navigate } = this.props.navigation;
navigate('Detail');
}
}
// ==============
// Detail Screen
// ==============
class DetailScreen extends Component {
static navigationOptions = {
title: 'Detail',
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Detail Page</Text>
</View>
);
}
}
// ==============
// Routing
// ==============
const ModelStack = StackNavigator({
Profile: { screen: ProfileScreen },
Detail: { screen: DetailScreen },
});
export default ModelStack;