Props والتمرير بين المكونات — أساسيات React Native
Props في React Native
ما هي Props؟
Props (اختصار Properties) هي طريقة لتمرير البيانات من مكون أب إلى مكون ابن.
مثال بسيط
// المكون الابن
function Greeting({ name, age }) {
return (
<View>
<Text>مرحباً {name}!</Text>
<Text>عمرك {age} سنة</Text>
</View>
);
}
// المكون الأب
function App() {
return (
<View>
<Greeting name="أحمد" age={25} />
<Greeting name="محمد" age={30} />
</View>
);
}أنواع Props المختلفة
1. نصوص
<MyComponent title="عنوان" />2. أرقام
<MyComponent count={10} />3. دوال (callbacks)
<MyComponent onPress={() => console.log('تم الضغط')} />4. كائنات
<MyComponent user={{ name: 'أحمد', age: 25 }} />5. مصفوفات
<MyComponent items={['عنصر1', 'عنصر2']} />6. مكونات (children)
<Card>
<Text>محتوى داخل البطاقة</Text>
</Card>
function Card({ children }) {
return (
<View style={styles.card}>
{children}
</View>
);
}القيم الافتراضية
function Button({ title = 'اضغط هنا', color = '#3b82f6' }) {
return (
<TouchableOpacity style={{ backgroundColor: color }}>
<Text>{title}</Text>
</TouchableOpacity>
);
}
function Actions() {
return (
<>
{/* استخدام بدون props: القيم الافتراضية */}
<Button />
{/* استخدام مع props مخصصة */}
<Button title="إرسال" color="#10b981" />
</>
);
}TypeScript مع Props
interface ButtonProps {
title: string;
onPress: () => void;
color?: string;
disabled?: boolean;
}
function Button({ title, onPress, color = '#3b82f6', disabled = false }: ButtonProps) {
return (
<TouchableOpacity
onPress={onPress}
disabled={disabled}
style={{
backgroundColor: disabled ? '#ccc' : color,
padding: 15,
borderRadius: 10,
}}
>
<Text style={{ color: '#fff' }}>{title}</Text>
</TouchableOpacity>
);
}مثال تطبيقي: مكون بطاقة قابل لإعادة الاستخدام
// Card.js
function Card({ title, description, image, onPress, footer }) {
return (
<TouchableOpacity onPress={onPress} style={styles.card}>
{image && (
<Image source={{ uri: image }} style={styles.cardImage} />
)}
<View style={styles.cardContent}>
<Text style={styles.cardTitle}>{title}</Text>
{description && (
<Text style={styles.cardDescription}>{description}</Text>
)}
</View>
{footer && (
<View style={styles.cardFooter}>{footer}</View>
)}
</TouchableOpacity>
);
}
// الاستخدام
<Card
title="دورة React Native"
description="تعلم بناء تطبيقات الموبايل"
image="https://example.com/image.jpg"
onPress={() => navigation.navigate('CourseDetails')}
footer={
<View style={{ flexDirection: 'row' }}>
<Text>⭐ 4.8</Text>
<Text>👥 1000 طالب</Text>
</View>
}
/>اختبر فهمك