0Pricing
React Native Academy · บทเรียน

การแสดงรูปภาพจากแหล่งข้อมูลภายในและระยะไกล

โหลดรูปภาพจากโฟลเดอร์ทรัพยากรและ URL ระยะไกลด้วยคอมโพเนนต์ Image กำหนด resizeMode และแสดงตัวแทนระหว่างโหลด

การแสดงรูปภาพจากแหล่งข้อมูลภายในและระยะไกล เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

The Image Component Introduction

The Image component shows photos, icons, and art. Just remember to give it a width and height — without a size it renders as an invisible empty box.

import { Image, View, StyleSheet } from 'react-native';

export default function SimpleImage() {
  return (
    <View style={{ padding: 16 }}>
      <Image
        source={{ uri: 'https://picsum.photos/200/200' }}
        style={styles.image}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  image: {
    width: 200,
    height: 200,
  },
});

Loading Local Images with require()

Show an image from your assets with require() and a fixed path. It gets bundled into your app at build time, so it loads instantly and works offline.

import { Image, StyleSheet } from 'react-native';

export default function LocalImage() {
  return (
    <Image
      source={require('./assets/icon.png')}
      style={styles.logo}
    />
  );
}

const styles = StyleSheet.create({
  logo: {
    width: 100,
    height: 100,
  },
});

// You can also provide @2x and @3x variants:
// assets/icon.png
// assets/icon@2x.png  ← used on 2× screens
// assets/icon@3x.png  ← used on 3× screens

Loading Remote Images from URLs

For an online image, pass a uri object to source. React Native fetches and caches it, but you still set a size, since it cannot know the dimensions yet.

import { Image, StyleSheet } from 'react-native';

export default function RemoteImage() {
  const imageUri = 'https://picsum.photos/seed/react-native/300/200';

  return (
    <Image
      source={{ uri: imageUri }}
      style={styles.photo}
    />
  );
}

const styles = StyleSheet.create({
  photo: {
    width: '100%',   // fill container width
    height: 200,     // fixed height
    borderRadius: 12,
  },
});

resizeMode: Fitting Images in Containers

The resizeMode prop fits an image to its box: "cover" fills and crops, while "contain" shows the whole thing. Use cover for photos, contain for logos.

import { Image, View, Text, StyleSheet } from 'react-native';

export default function ResizeModes() {
  const uri = 'https://picsum.photos/400/300';
  const box = { width: 150, height: 100, borderWidth: 1, borderColor: '#ccc' };

  return (
    <View style={{ flexDirection: 'row', gap: 8, padding: 16 }}>
      <View>
        <Image source={{ uri }} style={[box, { resizeMode: 'cover' }]} />
        <Text>cover</Text>
      </View>
      <View>
        <Image source={{ uri }} style={[box, { resizeMode: 'contain' }]} />
        <Text>contain</Text>
      </View>
    </View>
  );
}

Loading Placeholders and defaultSource

Online images take a moment, so show a placeholder while you wait. Track a loading state and swap in a spinner until the image loads.

import { Image, View, ActivityIndicator, StyleSheet } from 'react-native';
import { useState } from 'react';

export default function ImageWithLoader() {
  const [loading, setLoading] = useState(true);

  return (
    <View style={styles.container}>
      {loading && (
        <ActivityIndicator
          style={StyleSheet.absoluteFill}
          size='large'
          color='#999'
        />
      )}
      <Image
        source={{ uri: 'https://picsum.photos/300/200' }}
        style={styles.image}
        onLoad={() => setLoading(false)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { width: 300, height: 200, backgroundColor: '#f0f0f0', borderRadius: 12 },
  image: { width: 300, height: 200, borderRadius: 12 },
});

onLoad, onError, and onLoadStart

Image gives you callbacks: onLoadStart, onLoad, and onError. Use onError to show a fallback when a URL is wrong or the network drops.

import { Image, Text, View, StyleSheet } from 'react-native';
import { useState } from 'react';

export default function RobustImage({ uri, fallback }) {
  const [failed, setFailed] = useState(false);

  if (failed) {
    return (
      <View style={styles.fallback}>
        <Text style={{ color: '#999' }}>Image unavailable</Text>
      </View>
    );
  }

  return (
    <Image
      source={{ uri: failed ? null : uri }}
      defaultSource={fallback}
      style={styles.img}
      onError={(e) => {
        console.warn('Image failed:', e.nativeEvent.error);
        setFailed(true);
      }}
    />
  );
}

const styles = StyleSheet.create({
  img: { width: 200, height: 200, borderRadius: 8 },
  fallback: { width: 200, height: 200, backgroundColor: '#eee', alignItems: 'center', justifyContent: 'center', borderRadius: 8 },
});

expo-image for Better Performance

For lots of images, try expo-image — a drop-in replacement with better caching, blurhash placeholders, and far less stutter in long lists.

import { Image } from 'expo-image';

// Install: npx expo install expo-image

export default function ExpoImageExample() {
  return (
    <Image
      source='https://picsum.photos/300/200'
      placeholder='LGF5]+Yk^6#M@-5c,1J5@[or[Q6.'
      contentFit='cover'
      transition={300}
      style={{ width: 300, height: 200, borderRadius: 12 }}
    />
  );
}
// placeholder is a blurhash string — generates a blurry
// color-correct placeholder before the real image loads.

Circular Images and Avatar Patterns

Round avatar? Wrap an Image in a square View, set borderRadius to half its width, and add overflow: hidden to clip it into a perfect circle.

import { Image, View, StyleSheet } from 'react-native';

export default function Avatar({ uri, size = 60 }) {
  const radius = size / 2;
  return (
    <View style={[
      styles.container,
      { width: size, height: size, borderRadius: radius }
    ]}>
      <Image
        source={{ uri }}
        style={{ width: size, height: size }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    overflow: 'hidden',
    backgroundColor: '#e0e0e0', // placeholder while loading
  },
});

Providing Headers for Protected Images

Some images need a login token. Pass headers in the source object and React Native sends them with the request. Never hardcode secrets — read them at runtime.

import { Image } from 'react-native';

export default function ProtectedImage({ token }) {
  return (
    <Image
      source={{
        uri: 'https://api.myapp.com/user/avatar',
        headers: {
          Authorization: 'Bearer ' + token,
          'Cache-Control': 'no-cache',
        },
        // Optional: cache policy
        cache: 'reload',
      }}
      style={{ width: 80, height: 80, borderRadius: 40 }}
    />
  );
}

ImageBackground for Overlaid Content

Want content on top of a photo? ImageBackground works like a View with an image behind it. Give it a size and place children right over the picture.

import { ImageBackground, View, Text, StyleSheet } from 'react-native';

export default function HeroSection() {
  return (
    <ImageBackground
      source={{ uri: 'https://picsum.photos/400/300' }}
      style={styles.hero}
      imageStyle={{ borderRadius: 16 }}
    >
      {/* Content rendered on top of the image */}
      <View style={styles.overlay}>
        <Text style={styles.title}>Discover React Native</Text>
        <Text style={styles.subtitle}>Build mobile apps today</Text>
      </View>
    </ImageBackground>
  );
}

const styles = StyleSheet.create({
  hero: { width: '100%', height: 220, justifyContent: 'flex-end' },
  overlay: { backgroundColor: 'rgba(0,0,0,0.45)', padding: 16, borderBottomLeftRadius: 16, borderBottomRightRadius: 16 },
  title: { color: '#fff', fontSize: 22, fontWeight: 'bold' },
  subtitle: { color: '#ddd', fontSize: 14 },
});

Image Caching and Performance Tips

For smooth scrolling lists, keep image URLs stable, lean on expo-image caching, and prefetch key images before they appear. Goodbye, flicker.

import { Image } from 'react-native';
import { useEffect } from 'react';

// Pre-fetch images before they're needed
function usePrefetchImages(urls) {
  useEffect(() => {
    urls.forEach(url => {
      Image.prefetch(url).catch(() => {
        // ignore prefetch errors
      });
    });
  }, [urls]);
}

// Usage:
const imageUrls = [
  'https://example.com/photo1.jpg',
  'https://example.com/photo2.jpg',
];
usePrefetchImages(imageUrls);

Quick Check

Quick check! See how the Image pieces clicked. 📸

Lesson Recap

Well done! require() loads local images, a uri object loads remote ones, and resizeMode: "cover" fills a box. Next up: building a profile card.

คำถามที่พบบ่อย

บทเรียน “การแสดงรูปภาพจากแหล่งข้อมูลภายในและระยะไกล” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การแสดงรูปภาพจากแหล่งข้อมูลภายในและระยะไกล” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การแสดงรูปภาพจากแหล่งข้อมูลภายในและระยะไกล”

โหลดรูปภาพจากโฟลเดอร์ทรัพยากรและ URL ระยะไกลด้วยคอมโพเนนต์ Image กำหนด resizeMode และแสดงตัวแทนระหว่างโหลด คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การแสดงรูปภาพจากแหล่งข้อมูลภายในและระยะไกล” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม

ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. คอมโพเนนต์ View ในฐานะตัวครอบ
  2. การแสดงข้อความและการจัดรูปแบบแบบอักษร
  3. การแสดงรูปภาพจากแหล่งข้อมูลภายในและระยะไกล
  4. การประกอบการ์ดโปรไฟล์อย่างง่าย
← กลับไปที่ React Native Academy