[英]How to call a function from another .js file in React Native Expo
我是 React 的新手,我遇到过这样的问题:
我有一个带有按钮的 Main.js 文件:
import * as React from 'react';
import { StyleSheet, Text, View, SafeAreaView, Pressable, Alert } from 'react-native';
import { MaterialIcons, MaterialCommunityIcons} from '@expo/vector-icons';
import { DrawerActions } from '@react-navigation/native';
import Scanner from './Scanner'
export default function Main({ navigation }) {
return (
....
<View style={styles.container}>
<Pressable style={styles.button} onPress={ <Scanner() function call> }>
<Text style={styles.buttonText}>Take charger</Text>
</Pressable>
</View>
);
}
我有另一个文件 Scanner.js:
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
export default function Scanner() {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
alert(`Bar code with type ${type} and data ${data} has been scanned!`);
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.container}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
{scanned && <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
}
});
如何在 Main.js 中的 Main() function 中单击按钮时从 Scanner.js 调用 function Scanner()。 我试过 onPress={() => Scanner} 但由于使用了错误的钩子,它对我不起作用。
你应该在父组件 -> Main.js 中编写 function Scan 并将其转发给子组件 -> Scanner.js。 那叫道具钻https://blogs.perficient.com/2021/12/03/understanding-react-context-and-property-prop-drilling/#:~:text=Prop%20drilling%20refers%20to%20the,因为 %20of%20its%20repetitive%20code 。
这不是一个好模式,但你可以这样做。 您可以在父级中创建 function 并将其作为道具发送给子级,或者您可以使用来自 React 的上下文挂钩,该挂钩允许您将 function 从子级传递给父级。 另一种方法是使用 forwardRef,这将使您可以从父级调用子级 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.