Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

402
Visualizações
How to call a function from another .js file in React Native Expo

I'm new to React and I've faced such a problem:

I have Main.js file with a button:

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

An I have another file 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',
  }
}); 

How can I call a function Scanner() from Scanner.js on button click in the Main() function in Main.js. I've tried onPress={() => Scanner} but it didn't work for me because of wrong hooks usage.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You should write function Scan in the parent component -> Main.js and forward it to the children component -> Scanner.js. That's called prop drilling https://blogs.perficient.com/2021/12/03/understanding-react-context-and-property-prop-drilling/#:~:text=Prop%20drilling%20refers%20to%20the,because%20of%20its%20repetitive%20code.

about 4 years ago · Juan Pablo Isaza Relatório

0

This is not a good patern, but you can do that. You can create the function in the parent and send it as a prop to the child or you can use context hook from react, that hook lets you pass the function from the child to the parent. Another method is to use forwardRef, this will let you call the child function from the parent.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda