کامپوننت جدید ImageBackground در React Native


سلام دوستان.در این آموزش متنی قصدداریم یاد بگیریم چجوری از کامپوننت جدید React Native یعنی ImageBackground استفاده کنیم.React Native به تازگی یک کامپوننت جدید به نام ImageBackground معرفی کرد که بطور ویژه برای Image Background منتشر شده است.تا قبل از معرفی این کامپوننت ما مجبور بودیم از یک View یا Text استفاده کنیم و با استفاده از style اون رو بالای عکس قرار بدیم.با استفاده از این کامپوننت ما به راحتی میتونیم یک background images تمام صفحه ایجاد کنیم.شما میتونید اطلاعات بیشتر در مورد این کامپوننت رو از داکیومنت سایت react مشاهده کنید.
توجه کنید: قبل از اینکه از کامپوننت ImageBackground استفاده کنید اگر از Image به عنوان background استفده کنید در پلتفرم Ios با error مواجه خواهید شد.برای رفع این error باید در استایل View یا Text از backgroundColor: ‘transparent’ استفاده کنید.
1.ایمپورت کردن کامپوننت های Platform, StyleSheet, View, Text و ImageBackground در پروژه.
1 2 3 |
import React, { Component } from 'react'; import { Platform, StyleSheet, View, Text, ImageBackground } from 'react-native'; |
2.اضافه کردن View در بلاک render’s return.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
render() { return ( <View style={styles.MainContainer}> </View> ); } |
3.اضافه کردن کامپوننت ImageBackground با کامپوننت Text درونش.شما میتونید هر کامپوننتی رو بر اساس نیازتون داخل ImageBackground قرار بدید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
render() { return ( <View style={styles.MainContainer}> <ImageBackground source = {{ uri: 'https://reactapp.ir/wp-content/uploads/motorcycle.jpg' }} style = {styles.imageStyle} > <Text style={{color: '#fff', fontSize: 20, textAlign: 'center'}}>Hello Guys Welcome to reactapp.ir</Text> </ImageBackground> </View> ); |
4.ایجاد استایل سفارشی
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const styles = StyleSheet.create({ MainContainer :{ flex:1, paddingTop: (Platform.OS) === 'ios' ? 20 : , alignItems: 'center', justifyContent: 'center', }, imageStyle:{ width: 200, height: 300, justifyContent: 'flex-end', alignItems: 'center' } }); |
5.کد کامل برنامه در فایل App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import React, { Component } from 'react'; import { Platform, StyleSheet, View, Text, ImageBackground } from 'react-native'; export default class App extends Component{ render() { return ( <View style={styles.MainContainer}> <ImageBackground source = {{ uri: 'https://reactapp.ir/wp-content/uploads/motorcycle.jpg' }} style = {styles.imageStyle} > <Text style={{color: '#fff', fontSize: 20, textAlign: 'center'}}>Hello Guys Welcome to reactapp.ir</Text> </ImageBackground> </View> ); } } const styles = StyleSheet.create({ MainContainer :{ flex:1, paddingTop: (Platform.OS) === 'ios' ? 20 : , alignItems: 'center', justifyContent: 'center', }, imageStyle:{ width: 200, height: 300, justifyContent: 'flex-end', alignItems: 'center' } }); |
دیدگاهتان را بنویسید