Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

404
Vistas
Cómo llamar a una función desde otro archivo .js en React Native Expo

Soy nuevo en React y me he enfrentado a este problema:

Tengo el archivo Main.js con un botón:

 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> ); }

Y tengo otro archivo 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', } });

¿Cómo puedo llamar a una función Scanner() desde Scanner.js al hacer clic en el botón en la función Main() en Main.js? Probé onPress={() => Scanner} pero no funcionó para mí debido al uso incorrecto de ganchos.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Debe escribir la función Escanear en el componente principal -> Main.js y enviarlo al componente secundario -> Scanner.js. Eso se llama perforación de apoyo https://blogs.perficient.com/2021/12/03/understanding-react-context-and-property-prop-drilling/#:~:text=Prop%20drilling%20refers%20to%20the, porque%20de%20es%20repetitivo%20código .

about 4 years ago · Juan Pablo Isaza Denunciar

0

Este no es un buen patrón, pero puedes hacerlo. Puede crear la función en el elemento principal y enviarla como accesorio al elemento secundario o puede usar el enlace de contexto de reaccionar, ese enlace le permite pasar la función del elemento secundario al elemento principal. Otro método es usar forwardRef, esto le permitirá llamar a la función secundaria desde el padre.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda