Let's say we want to change the title of our application every time the user clicks on a button. First, we import useEffect and useState from the React library:
import React, { useState, useEffect } from 'react';import { View, Text, Button } from 'react-native';
Then, we create our component and use useState to handle the state of the application's title:
const App = () => {const [title, setTitle] = useState('Mi aplicación');useEffect(()=>{console.log('El componente se ha montado en la pantalla');},[])return (<View><Text>{title}</Text><Buttontitle="Cambiar título"onPress={() => setTitle('Nuevo título')}/></View>);};export default App;
In this example, we've used useState to handle the state of the application's title. setTitle is a function that allows us to update the state of the title when the user clicks on the button.
We've also used useEffect to log a message to the console every time the component mounts to the screen. We've added an empty second argument ([]) to indicate that this function should only be executed once, when the component mounts to the screen for the first time.
Finally, we've added a button that allows the user to change the application's title. When the user clicks on the button, the setTitle function is called to update the state of the title and change the text that is displayed on the screen.
With this, every time the user clicks on the button, the title of the application will be updated. I hope this example has helped you understand how to use useEffect with a simple button in React Native.
No hay comentarios:
Publicar un comentario