Image and ScrollView
Glissez pour afficher le menu
React Native provides several core components for building mobile applications, and two of the most versatile are Image and ScrollView. The Image component is used to display images from local files or remote URLs. It accepts several props, but the most important is source, which tells React Native where to find the image. The style prop allows you to control the appearance of the image, such as its width, height, border radius, and more. Other useful props include resizeMode for controlling how the image scales and accessibilityLabel for improving accessibility.
When you have more content than can fit on the screen, the ScrollView component comes into play. It creates a scrollable container that can hold multiple child components, including Image, Text, and others. This is especially useful for displaying lists of images or long blocks of text that users need to scroll through.
To see how these components work together, consider a simple example where you want to display a gallery of images with captions. By wrapping several Image and Text components inside a ScrollView, you allow users to scroll through the gallery vertically.
Here is a code sample that demonstrates this pattern:
import React from 'react';
import { ScrollView, Image, Text, View, StyleSheet } from 'react-native';
export default function ImageGallery() {
return (
<ScrollView>
<View style={styles.container}>
<Image
source={{ uri: 'https://placekitten.com/300/200' }}
style={styles.image}
/>
<Text style={styles.caption}>Cute Kitten 1</Text>
<Image
source={{ uri: 'https://placekitten.com/301/200' }}
style={styles.image}
/>
<Text style={styles.caption}>Cute Kitten 2</Text>
<Image
source={{ uri: 'https://placekitten.com/302/200' }}
style={styles.image}
/>
<Text style={styles.caption}>Cute Kitten 3</Text>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
paddingVertical: 16,
},
image: {
width: 300,
height: 200,
marginVertical: 8,
borderRadius: 12,
},
caption: {
fontSize: 16,
marginBottom: 12,
},
});
In this example, the ScrollView wraps a View that contains three pairs of Image and Text components. Each Image uses the source prop with a remote image URL and applies custom styles for consistent sizing and rounded corners. The Text component below each image serves as a caption. The ScrollView ensures that users can scroll to see all images, even if they do not all fit on the screen at once.
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion