Skip to content

Image(图片组件)

React Native 核心基础

在 React Native 中,Image 是用于显示图片的核心组件。它支持从本地文件、网络 URL 或资源文件中加载图片。

1. 什么是 Image 组件?

Image 组件是 React Native 中用于显示图片的基本组件。它支持多种图片来源、样式和加载状态管理。

主要功能

  • 图片加载:支持从本地文件、网络 URL 或资源文件加载图片
  • 图片样式:支持调整图片大小、裁剪、缩放等
  • 加载状态:支持处理图片加载过程中的各种状态
  • 可访问性:支持可访问性属性

2. 基本用法

从网络加载图片

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

export default function NetworkImage() {
  return (
    <View style={styles.container}>
      <Image
        source={{ uri: 'https://example.com/image.jpg' }}
        style={styles.image}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    width: 200,
    height: 200,
  },
});

从本地文件加载图片

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

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    width: 200,
    height: 200,
  },
});

带加载状态的图片

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

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

  return (
    <View style={styles.container}>
      {loading && (
        <ActivityIndicator size="large" color="#0000ff" />
      )}
      <Image
        source={{ uri: 'https://example.com/image.jpg' }}
        style={styles.image}
        onLoad={() => setLoading(false)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    width: 200,
    height: 200,
  },
});

3. 常用属性

核心属性

属性描述示例
source图片来源source={ { uri: 'https://example.com/image.jpg' } }source={require('../assets/image.png')}
style样式对象或样式数组style={ { width: 200, height: 200, borderRadius: 10 } }
resizeMode图片缩放模式resizeMode="cover"
testID用于测试的标识符testID="image"
accessible是否可访问accessible={true}
accessibilityLabel可访问性标签accessibilityLabel="Profile picture"

事件属性

属性描述示例
onLoad图片加载完成事件onLoad={() => console.log('Image loaded')}
onLoadStart图片开始加载事件onLoadStart={() => console.log('Image started loading')}
onLoadEnd图片加载结束事件onLoadEnd={() => console.log('Image loading ended')}
onError图片加载错误事件onError={() => console.log('Image loading error')}

4. 图片缩放模式

模式描述
cover保持宽高比,使图片完全覆盖容器,可能会裁剪
contain保持宽高比,使图片完全包含在容器内
stretch拉伸图片以适应容器,不保持宽高比
center居中显示图片,不缩放
repeat重复显示图片以填充容器

示例

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

export default function ResizeModeExample() {
  return (
    <View style={styles.container}>
      <View style={styles.item}>
        <Text>cover</Text>
        <Image
          source={{ uri: 'https://example.com/image.jpg' }}
          style={[styles.image, { resizeMode: 'cover' }]}
        />
      </View>
      <View style={styles.item}>
        <Text>contain</Text>
        <Image
          source={{ uri: 'https://example.com/image.jpg' }}
          style={[styles.image, { resizeMode: 'contain' }]}
        />
      </View>
      <View style={styles.item}>
        <Text>stretch</Text>
        <Image
          source={{ uri: 'https://example.com/image.jpg' }}
          style={[styles.image, { resizeMode: 'stretch' }]}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 20,
  },
  item: {
    alignItems: 'center',
  },
  image: {
    width: 100,
    height: 100,
    backgroundColor: '#f0f0f0',
  },
});

5. 性能优化

1. 图片缓存

  • React Native 的 Image 组件会自动缓存网络图片
  • 对于频繁使用的图片,考虑使用本地资源文件

2. 图片尺寸优化

  • 为不同屏幕尺寸提供合适大小的图片
  • 使用适当的图片格式(如 WebP)以减小文件大小

3. 懒加载

  • 对于长列表中的图片,实现懒加载
  • 只有当图片进入视口时才加载
jsx
import { FlatList, Image, StyleSheet, View } from 'react-native';

const images = [
  { id: '1', uri: 'https://example.com/image1.jpg' },
  { id: '2', uri: 'https://example.com/image2.jpg' },
  { id: '3', uri: 'https://example.com/image3.jpg' },
  // 更多图片...
];

export default function LazyLoadImages() {
  return (
    <FlatList
      data={images}
      keyExtractor={(item) => item.id}
      renderItem={({ item }) => (
        <View style={styles.item}>
          <Image
            source={{ uri: item.uri }}
            style={styles.image}
            resizeMode="cover"
          />
        </View>
      )}
    />
  );
}

const styles = StyleSheet.create({
  item: {
    height: 200,
    marginVertical: 10,
  },
  image: {
    flex: 1,
  },
});

4. 避免不必要的重新渲染

  • 使用 React.memo 包装图片组件,避免不必要的重新渲染
  • 避免在 render 方法中创建新的 source 对象
jsx
import React, { memo } from 'react';
import { Image, StyleSheet } from 'react-native';

const MemoizedImage = memo(({ uri }) => {
  console.log('MemoizedImage rendered');
  return (
    <Image
      source={{ uri }}
      style={styles.image}
    />
  );
});

export default function OptimizedImage() {
  return (
    <View>
      <MemoizedImage uri="https://example.com/image.jpg" />
    </View>
  );
}

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

6. 常见错误与解决方案

错误 1:图片不显示

错误

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

export default function App() {
  return (
    <View style={styles.container}>
      <Image
        source={{ uri: 'https://example.com/image.jpg' }}
        // 错误:没有设置宽高
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

解决方案

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

export default function App() {
  return (
    <View style={styles.container}>
      <Image
        source={{ uri: 'https://example.com/image.jpg' }}
        style={styles.image} // 正确:设置宽高
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    width: 200,
    height: 200,
  },
});

错误 2:本地图片路径错误

错误

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

export default function App() {
  return (
    <View style={styles.container}>
      <Image
        source={require('./image.png')} // 错误:路径可能不正确
        style={styles.image}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    width: 200,
    height: 200,
  },
});

解决方案

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

export default function App() {
  return (
    <View style={styles.container}>
      <Image
        source={require('../assets/image.png')} // 正确:使用相对路径
        style={styles.image}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    width: 200,
    height: 200,
  },
});

错误 3:网络图片加载失败

错误

  • 图片 URL 无效
  • 网络连接问题
  • 跨域问题

解决方案

  • 检查图片 URL 是否正确
  • 确保设备有网络连接
  • 处理加载错误事件
jsx
import { View, Image, StyleSheet, Text } from 'react-native';
import { useState } from 'react';

export default function App() {
  const [error, setError] = useState(false);

  return (
    <View style={styles.container}>
      {error ? (
        <Text>Image loading failed</Text>
      ) : (
        <Image
          source={{ uri: 'https://example.com/image.jpg' }}
          style={styles.image}
          onError={() => setError(true)}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    width: 200,
    height: 200,
  },
});

7. 最佳实践

1. 图片资源管理

  • 为不同屏幕密度提供不同分辨率的图片
  • 使用适当的图片格式,如 WebP 以减小文件大小
  • 对于小图标,考虑使用矢量图标库(如 react-native-vector-icons)

2. 加载状态处理

  • 为图片添加加载指示器
  • 处理加载错误,显示占位图
  • 实现图片预加载

3. 性能优化

  • 对于长列表,使用虚拟化(如 FlatList)
  • 实现图片懒加载
  • 避免在 render 方法中创建新的 source 对象

4. 可访问性

  • Image 组件添加适当的 accessibilityLabel
  • 对于装饰性图片,设置 accessible={false}

8. 总结

Image 是 React Native 中用于显示图片的核心组件。通过合理使用 Image 组件,你可以在应用中显示各种类型的图片。

在使用 Image 组件时,要注意:

  1. 为图片设置适当的宽高
  2. 选择合适的图片缩放模式
  3. 处理图片加载状态和错误
  4. 考虑性能优化,特别是对于长列表中的图片

掌握 Image 组件的使用,是创建视觉吸引力强的 React Native 应用的基础。在接下来的教程中,我们将学习更多的核心组件,如 TextInputScrollView 等。

© 2026 编程马·菜鸟教程 版权所有