好的伙计们,所以我有一个问题,我是反应原生开发的新手,并且在使用StackNavigator时遇到了问题。当我按下一个用于导航当前屏幕的按钮时,它会给我一个这样的错误:在此处输入图像描述
这是我正在使用的代码,我无法让它工作,
static navigationOptions = {
title: 'Welcome',
};
<Button
onPress={() => navigate('News')}
title="News"
/>
const NewsApp = StackNavigator({
Home: { screen: Splash },
News: { screen: News }
});
如果您
确实尝试从创建它的组件进行导航,您将无法访问导航器,因为它只会将导航注入NewsApp
中的任何内容。
您应该在导航堆栈中最顶层的组件内处理后压。但是,如果您需要控制诸如您拥有的地方的导航,那么实现redux对您来说可能是一个很好的解决方案。
在渲染函数中,您必须像这样提取导航器:
render()
{
const { navigate } = this.props.navigation;
return (
<Button
onPress={() => navigate('News')}
title="News"
/>
)
}
堆栈导航入门:
//First Screen
import {
StackNavigator,
} from 'react-navigation';
//Added screens to navigate.
const BasicApp = StackNavigator({
Main: {screen: MainScreen},
Profile: {screen: ProfileScreen},
});
//Second screen (Main Screen)
//This is a welcome screen which appears first in the route declared in the previous code
class MainScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
//constant for navigation
const { navigate } = this.props.navigation;
return (
<Button
title="Go to Jane's profile"
onPress={() =>
navigate('Profile', { name: 'Jane' })//Navigate to Profile with name
}
/>
);
}
}
//Third screen (Profile screen)
class ProfileScreen extends React.Component {
static navigationOptions = ({navigation}) => ({
title: navigation.state.params.name, //extracted name from the params
});
render() {
const { goBack } = this.props.navigation;//used to goBack prop
return (
<Button
title="Go back"
onPress={() => goBack()}
/>
);
}
}
干杯:)