React Native的新手。我已经阅读了堆栈导航器文档,但仍然不知道如何执行此操作。
所以我有一个底部的标签导航器,并且我想在其中一个标签中实现一个堆栈导航器,所以我可以从主标签屏幕导航到第二个屏幕,但是不能从第二个屏幕导航到第三个屏幕因为它找不到变量“ navigation”,这是可以理解的,因为我为每个屏幕使用了不同的js文件。如何将导航变量传递到另一个屏幕?下面是我的代码:
OrderScreen.js:
imports...
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
const styles = StyleSheet.create({
...
}
});
function Orderscreen({ navigation }) {
return (
<View style={styles.welcome}>
<View styles={styles.container}>
<Button style={styles.button1} color="warning" uppercase onPress={() => { navigation.navigate('Scan QR code') }}><Text style={styles.buttonText}>Take me to screen SCAN QR CODE</Text></Button>
</View>
</View>
)
};
import { Qrcodescanner } from './qrcodescanner';
import { Menu } from './menu';
import { render } from 'react-dom';
function MenuScreen({ navigation }) {
return(
<Menu></Menu>
)
}
function QRScanScreen({ navigation }) {
return(
<Qrcodescanner></Qrcodescanner>
)
}
export default function App() {
return (
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={Orderscreen} />
<Stack.Screen name="Scan QR code" component={QRScanScreen}
options={{
headerRight: () => (
<Button shadowless
onlyIcon icon="question" iconFamily="antdesign" iconSize={30} color="info" iconColor="#fff" style={{ width: 35, height: 35, marginRight: 20 }}
/>
),
}}
/>
<Stack.Screen name="Menu" component={MenuScreen} />
</Stack.Navigator>
);
}
Qrcodescanner.js:
export class Qrcodescanner extends React.Component {
...
render() {
const { hasCameraPermission, scanned } = this.state;
if (hasCameraPermission === null) {
return <Text> Requesting for camera permission </Text>;
}
if (hasCameraPermission === false) {
return <Text> No access to camera </Text>;
}
return (
<View
style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-end',
}}> ...
</View>
);
}
handleBarCodeScanned = ({ type, data}) => {
this.setState({
scanned: true,
});
alert(`Bar code with type ${type} and data ${data} has been scanned!`);
navigation.navigate('Menu')
};
};
因此,当我扫描某些东西时,它应该导航到“菜单”屏幕,但我收到错误消息:“找不到变量:导航”。如何将导航变量传递到其他js文件?
答案 0 :(得分:0)
我已经看到了您的鳕鱼并为您找到了解决方案,您只需创建一个新文件NavigationServices.js
import { NavigationActions } from "react-navigation";
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params
})
);
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator
};
,然后将文件导入您的.js
文件中,并使用它像在OrderScreen.js:
中导航
import NavigationService from "../NavigationService";
并像这样使用它。
NavigationService.navigate("Qrcodescanner");