我有4页:App.js,HomeScreen.js,Login.js,Toolbar.js
使用StackNavigator的我的应用页面:
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import { StackNavigator, DrawerNavigator } from 'react-navigation';
import Splash from './screens/Splash';
import HomeScreen from './screens/HomeScreen';
import Login from './screens/Login';
import Lobby from './screens/Lobby';
import Wifi from './screens/Wifi';
import Toolbar from './components/ToolBar/Toolbar';
import Mobile from './screens/Mobile';
;
const Navigation = StackNavigator({
Splash:{screen: Splash},
HomeScreen:{screen: HomeScreen},
Login:{screen: Login},
Lobby:{screen: Lobby},
Wifi:{screen: Wifi},
Mobile:{screen:Mobile}
}, {
mode: 'modal',
headerMode: 'none'
});
export default Navigation;
我正在将工具栏导入HomeScreen,并希望将导航道具从HomeScreen传递到工具栏,以便我可以从工具栏和HomeScreen访问“登录”页面。
我的工具栏页面:
import React,{Component} from 'react';
import {Text, View, Button, StyleSheet, TouchableOpacity,
Dimensions,
Image,ScrollView, Picker, FlatList} from 'react-native';
import { StackNavigator, DrawerNavigator } from 'react-navigation';
import config from '../../components/config/index';
class Toolbar extends Component{
constructor(){
super()
this.state = {
}
}
render(){
//const {navigate} = this.props.navigation;
return(
<View style={styles.mainToolbar}>
<View style={styles.containerForThree}>
<View style={styles.leftArrowContainer}>
<TouchableOpacity
onPress={()=>navigate('Login')}
>
<Text>hello</Text>
</TouchableOpacity>
</View>
截至目前,我已将const导航注释掉,因为如果出现HomeScreen,它将不会加载。
主屏幕:
import React,{Component} from 'react';
import {
AppRegistry, StyleSheet, Text, View, Image, ScrollView, Button, TouchableOpacity, Dimensions
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import Toolbar from '../components/ToolBar/Toolbar';
export default class HomeScreen extends Component {
static navigationOptions ={
title: 'Home Screen'
};
onValueChange(value, idx){
this.setState({
language: value
})
AsyncStorage.setItem('language', value)
}
render(){
var {navigate} = this.props.navigation;
return(
<View style={styles.scrollContainer}>
<Toolbar navigate={navigate}/>
<View>
<Text>Welcome To the SEcond Page</Text>
<Button
onPress={
()=>navigate("Login")
}
title="Go to Login"
/>
</View>
我试图通过导航道具从HomeScreen传递到工具栏
当我按下按钮时,它说找不到变量'导航'。但是,当我取消注释导航工具栏时,我得到错误TypeError:undefined不是一个对象(evaulating'his.props.navigation.navigate')
答案 0 :(得分:4)
在此您将道具navigate
传递给Toolbar
:
<Toolbar navigate={navigate}/>
因此您需要在render()
中引用它:
const { navigate } = this.props;
所以这只是一个小错误,但那是什么解决了它。
我个人鼓励将navigation
传递给Toolbar
:<Toolbar navigation={ this.props.navigation } />
。因此,您可以更好地了解导航对象。
答案 1 :(得分:2)
您可以与React导航的Navigation道具一起使用。如果要从组件导航。 https://reactnavigation.org/docs/en/connecting-navigation-prop.html
答案 2 :(得分:1)
这是将withNavigation
HOC包装到相应的组件中。这不像向孩子发送道具