8.1--21. Props

 

Dominando las Props en React Native: Comunicación entre Componentes

Las props (abreviatura de properties) son uno de los conceptos fundamentales en React Native. Permiten pasar datos entre componentes y hacer que tu interfaz sea dinámica y reutilizable.

¿Qué son las Props?

  • 🔹 Datos inmutables que fluyen de padre a hijo

  • 🔹 Configuran el comportamiento/apariencia de componentes

  • 🔹 Similar a los atributos en HTML

Implementación en Functional Components

jsx
import React from 'react';
import { View, StyleSheet, ColorValue } from 'react-native';

// Definimos la interfaz para las props
interface MiComponenteProps {
  color: ColorValue;
}

function MiComponente({ color }: MiComponenteProps) {
  return (
    <View style={[styles.circle, { backgroundColor: color }]} />
  );
}

const styles = StyleSheet.create({
  circle: {
    width: 50,
    height: 50,
    borderRadius: 25,
  },
});

export default MiComponente;

Uso del componente:

jsx
<MiComponente color="blue" />

Implementación en Class Components

jsx
import React from 'react';
import { View, StyleSheet, ColorValue } from 'react-native';

interface MiComponenteClassProps {
  color: ColorValue;
}

class MiComponenteClass extends React.Component<MiComponenteClassProps> {
  render() {
    const { color } = this.props;
    return (
      <View style={[styles.circle, { backgroundColor: color }]} />
    );
  }
}

// Mismos estilos que el componente funcional
export default MiComponenteClass;

Uso del componente:

jsx
<MiComponenteClass color="pink" />

Buenas Prácticas con Props

  1. Tipado fuerte con TypeScript:

    ts
    interface ButtonProps {
      mode: 'info' | 'error' | 'success';
      onPress: () => void;
      disabled?: boolean; // Prop opcional
    }
  2. Valores por defecto:

    jsx
    function MiComponente({ color = 'red' }: MiComponenteProps) {
      // ...
    }
  3. Desestructuración para mejor legibilidad

Caso Práctico: Componente Botón Reutilizable

jsx
interface ButtonProps {
  title: string;
  onPress: () => void;
  variant?: 'primary' | 'secondary';
}

function Button({ title, onPress, variant = 'primary' }: ButtonProps) {
  const backgroundColor = variant === 'primary' ? '#3498db' : '#e74c3c';
  
  return (
    <TouchableOpacity 
      style={[styles.button, { backgroundColor }]}
      onPress={onPress}
    >
      <Text style={styles.text}>{title}</Text>
    </TouchableOpacity>
  );
}

Uso:

jsx
<Button 
  title="Guardar" 
  onPress={handleSave} 
  variant="primary" 
/>

¿Props vs State?

PropsState
Inmutables (de padre)Mutables (con setState/useState)
Flujo unidireccionalInterno al componente
Configuración inicialDatos que cambian

🚀 Conclusión: Las props son esenciales para crear componentes flexibles y reutilizables. Combínalas con TypeScript para mayor seguridad y mantenibilidad.

¿Quieres profundizar en cómo manejar el estado? ¡No te pierdas nuestro próximo post sobre useState y this.state!

Comentarios

Entradas más populares de este blog

4.2-12. Componentes esenciales

7.5-10. ¿Como funcionan los estilos en React Native?

7.1-19. Creación de estilos