React Native - button a js file calling a function or variable in another js file

Asked

Viewed 50 times

0

I need some help here:

I have 2 js files: Header/index.js and Main/index.js

In Header/index.js there is a button: <TouchableOpacity onPress={() => {}} />

In Main/index.js you have:

const onPressTiming = () => {
    Animated.timing(translateY, {toValue: 380, duration: 300, useNativeDriver: true,}).start();
  }

I need to run the button on Header/index.js, when clicked run the "cost onPressTiming" of Main/index.js

Simply put, one button of a js file calling function or variable inside another js file.

1 answer

0

You can send the function as props to your Header component. To do this, in the construction of your file "Main", you can bind the function you want to use.

In the example below, the "Main" component sends the "delete" function to the "Delete" component".

import {Container} from "./styles.js";
import Excluir from "../../components/Excluir/index";
export default class Main extends Component {
  constructor(props) {
    super(props);
    this.deletar = this.deletar.bind(this);
  }

  deletar = async id => {
    try {
      //Executar comandos
    } catch (error) {
      //Em caso de erro
    }
  };

  
  render() {
    return (
      <Container>
      
        <Excluir
          deletar={this.deletar}
          codigo={1}
        />

      </Container>
    );
  }
}

In your "Delete" component, you could use the function created in "Main" in this way:

import {Container, RemoveButton, Title, Subtitle, TextButton} from "./styles.js";
const Excluir = ({deletar, codigo }) => (
  <Container>
    <Title>Remover</Title>
    <Subtitle>Tem certeza que deseja excluir?</Subtitle>
    <RemoveButton onPress={() => deletar(codigo)}><TextButton>Sim</TextButton></RemoveButton>
  </Container>
);
  • Blz! Thank you, it was very clear!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.