Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

319
Views
React Native: cómo crear elementos y devolverlos en una función

Soy nuevo en React Native

y quiero crear elementos y devolverlos con un botón en la función onPress , no quiero ocultarlos y mostrarlos como un Modal, sino crearlos.

 import React from "react" import { Button, StyleSheet, Text, View } from 'react-native'; function createElement() { return( <View style={styles.elementStyle}> <Text style={styles.txt}>ELement</Text> </View> ) } const App = () => { return ( <View style={{ flex: 1,backgroundColor: '#fff', alignItems: 'center',justifyContent: 'center',}}> <Button title="create element" onPress={() => createElement()}/> </View> ); } export default App; const styles = StyleSheet.create({ container: {flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, elementStyle: { backgroundColor:'grey', width:'95%', height: 90, margin: 10, justifyContent: "center", borderRadius: 10, fontWeight: "bold" }, txt: {textAlign:'center',fontSize:28,color:'#fff',fontWeight: "bold"}});

Probé con funciones que devuelven componentes, pero nada funciona

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

¿Quieres tener múltiples elementos o solo un modal?

Para elementos múltiples, haga lo siguiente. Para un solo elemento, es más fácil usar la lógica mostrar/ocultar.

La mejor manera de hacer esto es tener una matriz en estado como este:

const [elementArray, setElementArray] = useState();

En cambio, su método createElement debe convertirse en dos partes, agregando elementos a la matriz con el contenido que desea, que luego puede representar en la función de retorno principal con un método de mapa.

 const addElement = () => { // Just using text here. If you want a more complex element, you will have to add things to the object. const newElementText = 'Element'; const newElementArray = elementArray.slice(); newElementArray.push(newElementText); setElementArray([...newElementArray]); }

Luego, en su función de retorno en el componente:

 {elementArray.map((element) => { return ( <View style={styles.elementStyle}> <Text style={styles.txt}>element</Text> </View> ); } )}

Asegúrese de agregar un enlace useEffect para que el componente se vuelva a representar cuando agregue un nuevo elemento:

 useEffect(()=> {}, [elementArray])
about 4 years ago · Santiago Trujillo Report

0

No puede navegar a un componente como ese. Si lo está haciendo para que su componente aparezca al hacer clic en un botón, le sugiero que construya una pila importando react-native/navigation. Luego, construye tu estructura como se muestra. Es posible que mi explicación no haya sido la mejor porque su código inicial no estaba estructurado. Esto debería darte una respuesta aún mejor. documentos

 const navigation = useNavigation(); function createElement() { return( <View style={styles.elementStyle}> <Text style={styles.txt}>Element</Text> </View> ) } function Home() { return ( <View style={{ flex: 1,backgroundColor: '#fff', alignItems: 'center',justifyContent: 'center',}}> <Button title="create element" onPress={() => navigation.navigate("Element")}/> </View> ); } const App = () => { <Stack.Navigator screenOptions={{ headerShown: false }}> <Stack.Screen name="Home" component={Home} /> <Stack.Screen name="Element" component={CreateElement} /> </Stack.Navigator> }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!