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

320
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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