El componente View como contenedor
Utilice View como contenedor principal del diseño, anide varias Views para crear pantallas estructuradas y comprenda cómo se asigna a las cajas de interfaz de usuario nativas.
El componente View como contenedor es una lección gratuita de React Native Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de React Native Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de React Native Academy incluye 4 lecciones en total.
What Is the View Component?
Conoce View: la caja básica con la que construyes cada pantalla. Es un rectángulo que contiene otros componentes, el cual se asigna a una caja nativa real tanto en iOS como en Android.
import { View, Text } from 'react-native';
export default function App() {
return (
<View>
<Text>I am inside a View!</Text>
</View>
);
}View Maps to Native UI Boxes
Cada vista que escribes se convierte en un componente nativo real en el dispositivo, no en HTML dentro de un navegador. Es por eso que tu aplicación se siente tan fluida como una creada en Swift o Kotlin.
import { View, StyleSheet } from 'react-native';
// A simple colored box rendered natively
export default function Box() {
return (
<View style={styles.box} />
);
}
const styles = StyleSheet.create({
box: {
width: 100,
height: 100,
backgroundColor: '#4f86f7',
borderRadius: 12,
},
});Nesting Views for Structure
El verdadero poder es el anidamiento: coloca Vistas dentro de Vistas para crear filas, columnas y secciones. Cada Vista es un contenedor Flexbox, por lo que los elementos secundarios simplemente se alinean.
import { View, Text, StyleSheet } from 'react-native';
export default function Layout() {
return (
<View style={styles.screen}>
<View style={styles.header}>
<Text style={styles.headerText}>Header</Text>
</View>
<View style={styles.body}>
<Text>Body content here</Text>
</View>
<View style={styles.footer}>
<Text>Footer</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1 },
header: { height: 60, backgroundColor: '#333', justifyContent: 'center', alignItems: 'center' },
body: { flex: 1, padding: 16 },
footer: { height: 50, backgroundColor: '#eee', justifyContent: 'center', alignItems: 'center' },
headerText: { color: '#fff', fontWeight: 'bold' },
});View Styling: backgroundColor and Borders
Dale estilo a una View con la propiedad style. Utiliza backgroundColor, borderRadius, padding y margin, escritos en camelCase y con números simples, no "16px".
import { View, StyleSheet } from 'react-native';
export default function Card() {
return (
<View style={styles.card}>
{/* Children go here */}
</View>
);
}
const styles = StyleSheet.create({
card: {
backgroundColor: '#ffffff',
borderRadius: 16,
borderWidth: 1,
borderColor: '#e0e0e0',
padding: 20,
marginHorizontal: 16,
marginVertical: 8,
// Shadow (iOS)
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
// Shadow (Android)
elevation: 3,
},
});flex: 1 to Fill Available Space
Añade flex: 1 y una View se expandirá para rellenar a su elemento padre. Tu View de pantalla externa normalmente requiere esto para que se extienda por toda la pantalla.
import { View, StyleSheet } from 'react-native';
export default function SplitScreen() {
return (
<View style={{ flex: 1 }}>
{/* Top half */}
<View style={{ flex: 1, backgroundColor: '#4f86f7' }} />
{/* Bottom half */}
<View style={{ flex: 1, backgroundColor: '#f74f4f' }} />
</View>
);
}Absolute Positioning in View
¿Necesitas una capa superpuesta o un distintivo flotante? Establece position: absolute y luego colócalo con top, bottom, left y right. Saldrá del flujo normal de Flexbox.
import { View, Text, StyleSheet } from 'react-native';
export default function BadgeExample() {
return (
<View style={styles.container}>
<View style={styles.icon} />
{/* Badge overlaid in top-right corner */}
<View style={styles.badge}>
<Text style={styles.badgeText}>3</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: { width: 48, height: 48 },
icon: { width: 48, height: 48, backgroundColor: '#555', borderRadius: 8 },
badge: {
position: 'absolute',
top: -4, right: -4,
width: 20, height: 20,
borderRadius: 10,
backgroundColor: 'red',
alignItems: 'center', justifyContent: 'center',
},
badgeText: { color: '#fff', fontSize: 11, fontWeight: 'bold' },
});overflow: 'hidden' for Clipping
De forma predeterminada, una View permite que los elementos hijos sobresalgan de sus bordes. Añade overflow: hidden para recortarlos, lo cual es perfecto para avatares redondos o tarjetas con esquinas redondeadas.
import { View, Image, StyleSheet } from 'react-native';
export default function CircleAvatar() {
return (
<View style={styles.circle}>
<Image
source={{ uri: 'https://picsum.photos/80' }}
style={{ width: 80, height: 80 }}
/>
</View>
);
}
const styles = StyleSheet.create({
circle: {
width: 80,
height: 80,
borderRadius: 40,
overflow: 'hidden', // clips the image to the circle
},
});The pointerEvents Prop
La propiedad pointerEvents decide si un View captura los toques. Establécela en "none" para que los toques pasen directamente a través de él; es útil para superposiciones que no deberían bloquear el desplazamiento.
import { View, Text, StyleSheet } from 'react-native';
function LoadingOverlay({ visible }) {
if (!visible) return null;
return (
// 'box-none' — overlay blocks no touches (children can)
// Use 'auto' to block all interaction behind it
<View style={styles.overlay} pointerEvents='auto'>
<Text style={styles.text}>Loading...</Text>
</View>
);
}
const styles = StyleSheet.create({
overlay: {
...StyleSheet.absoluteFillObject,
backgroundColor: 'rgba(0,0,0,0.5)',
alignItems: 'center',
justifyContent: 'center',
},
text: { color: '#fff', fontSize: 18 },
});StyleSheet.absoluteFillObject
StyleSheet.absoluteFillObject es un atajo que hace que una vista (View) ocupe su contenedor de borde a borde. Utilízalo con el operador de propagación (spread) para crear superposiciones y cargadores de pantalla completa al instante.
import { View, StyleSheet } from 'react-native';
// Full-screen background overlay
const styles = StyleSheet.create({
overlay: {
...StyleSheet.absoluteFillObject,
backgroundColor: 'rgba(0, 0, 0, 0.6)',
zIndex: 999,
},
});
// Equivalent to:
// { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0,
// backgroundColor: 'rgba(0,0,0,0.6)', zIndex: 999 }SafeAreaView for Notch and Home Bar
Los teléfonos tienen muescas y barras de inicio. Envuelve tu pantalla en SafeAreaView y tu contenido se mantendrá libre de ellas, sin ocultarse nunca detrás del hardware.
import { SafeAreaView, StyleSheet, Text } from 'react-native';
// Or use from react-native-safe-area-context for more control
// import { SafeAreaView } from 'react-native-safe-area-context';
export default function App() {
return (
<SafeAreaView style={styles.container}>
<Text>This content avoids the notch!</Text>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});Platform-Specific View Styling
A veces, iOS y Android necesitan estilos diferentes. El módulo Platform ayuda: Platform.OS te indica cuál es, y Platform.select() selecciona el valor correcto.
import { View, Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
card: {
backgroundColor: '#fff',
borderRadius: 12,
padding: 16,
// Platform-specific shadows:
...Platform.select({
ios: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.15,
shadowRadius: 6,
},
android: {
elevation: 4,
},
}),
},
});Quick Check
¡Repaso rápido! Mira qué tan bien se te quedaron los conceptos básicos de View. 💪
Lesson Recap
¡Buen trabajo! View es tu contenedor nativo, flex: 1 hace que llene a su padre y SafeAreaView mantiene el contenido alejado de las muescas. Lo siguiente: mostrar texto.
Preguntas frecuentes
¿La lección «El componente View como contenedor» es gratis?
Sí — el texto completo de «El componente View como contenedor» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de React Native Academy, actualiza a CoddyKit PRO. El curso de React Native Academy incluye 4 lecciones en total.
¿Qué aprenderé en «El componente View como contenedor»?
Utilice View como contenedor principal del diseño, anide varias Views para crear pantallas estructuradas y comprenda cómo se asigna a las cajas de interfaz de usuario nativas. Practicas React Native Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar React Native Academy?
No se requiere experiencia previa. React Native Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «El componente View como contenedor»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de React Native Academy?
Sí. Cada lección de React Native Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- El componente View como contenedor
- Visualización de texto y estilos de fuente
- Visualización de imágenes locales y remotas
- Composición de una tarjeta de perfil sencilla