探索React Native的图像选择神器:react-native-image-picker ✨
import React from 'react';
import { View, Button, Image, StyleSheet } from 'react-native';
import ImagePicker from 'react-native-image-picker';
export default class ImagePickerExample extends React.Component {
state = {
avatarSource: null,
};
pickImage = () => {
ImagePicker.launchImageLibrary(
{
mediaType: 'photo',
quality: 0.5,
},
(response) => {
if (!response.didCancel) {
this.setState({ avatarSource: { uri: response.uri } });
}
}
);
};
render() {
let { avatarSource } = this.state;
return (
<View style={styles.container}>
<Button title="Pick an image" onPress={this.pickImage} />
{avatarSource && <Image source={avatarSource} style={styles.avatar} />}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
avatar: {
width: 150,
height: 150,
borderRadius: 75,
},
});
这段代码展示了如何使用react-native-image-picker
库来选择和显示图片。当用户点击按钮时,会打开图片库,用户选择图片后会自动显示在界面上的图像组件中。
评论已关闭