显示本地与远程来源的图像
使用 Image 组件从资源文件夹和远程网址加载图像,设置 resizeMode,并显示加载占位内容。
显示本地与远程来源的图像 是 CoddyKit 上的免费 React Native Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 React Native Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 React Native Academy 课程共包含 4 节课。
图片组件简介
图片组件用于显示照片、图标和插图。请记住为它设置宽度和高度——没有尺寸时,它会渲染成一个不可见的空框。
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,
},
});使用 require() 加载本地图片
使用 require() 和固定路径显示 assets 中的图片。图片会在构建时打包到应用中,因此加载速度快,也能离线使用。
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从 URL 加载远程图片
对于在线图片,请将包含 uri 的对象传给 source。React Native 会获取并缓存图片,但您仍需设置尺寸,因为它暂时无法知道图片的大小。
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:在容器中适配图片
resizeMode 属性用于让图片适配其框体:"cover" 会填满并裁剪图片,而 "contain" 会显示完整图片。照片使用 cover,徽标使用 contain。
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>
);
}加载占位内容和 defaultSource
在线图片需要一些加载时间,因此请在等待时显示占位内容。跟踪加载状态,并在图片加载完成前显示加载指示器。
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 和 onLoadStart
图片组件提供回调:onLoadStart、onLoad 和 onError。当 URL 错误或网络中断时,可以使用 onError 显示备用内容。
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 提升性能
如果需要显示大量图片,可以试试 expo-image——它是可直接替换的方案,提供更好的缓存、模糊哈希占位图,并能显著减少长列表中的卡顿。
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.圆形图片和头像模式
想要圆形头像吗?将图片包裹在方形视图中,把 borderRadius 设为宽度的一半,再添加 overflow: hidden,就能将其裁剪成完美的圆形。
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
},
});为受保护的图片提供请求标头
有些图片需要登录令牌。将 headers 传入 source 对象,React Native 就会在请求中发送它们。切勿将机密信息硬编码,而应在运行时读取。
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 叠加内容
想在照片上放置内容吗?ImageBackground 的作用类似于带背景图片的视图。为它设置尺寸,然后将子元素直接放到图片上方。
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 },
});图片缓存和性能提示
为了让列表滚动流畅,请保持图片 URL 稳定,充分利用 expo-image 的缓存,并在关键图片出现前预先加载它们。告别闪烁。
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);快速检查
快速检查一下!看看您是否掌握了图片的各个要点。📸
课程回顾
做得很好!require() 用于加载本地图片,包含 uri 的对象用于加载远程图片,而 resizeMode: "cover" 会填满框体。接下来:构建个人资料卡片。
用 AI 导师学习 JavaScript — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 30
- 课程
- 120
常见问题解答
「显示本地与远程来源的图像」课时是免费的吗?
是的 — 「显示本地与远程来源的图像」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Native Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Native Academy 课程共包含 4 节课。
「显示本地与远程来源的图像」这节课中我会学到什么?
使用 Image 组件从资源文件夹和远程网址加载图像,设置 resizeMode,并显示加载占位内容。 你通过在浏览器中直接运行的动手代码来练习 React Native Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 React Native Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 React Native Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「显示本地与远程来源的图像」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 React Native Academy 课中编写并运行代码吗?
能。每节 React Native Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 作为容器的 View 组件
- 显示文本与设置字体样式
- 显示本地与远程来源的图像
- 组合一个简单的个人资料卡片