如果想实现点击按钮访问相册,并让图片显示在应用中我们可以使用react-native-image-picker
首先
npm i react-native-image-picker@5.3.1
Android配置环境:
路径:android/app/src/main/AndroidManifest.xml
添加以下代码:
<!-- 访问相册 -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
找到android/settings.gradle
添加以下代码:
/* 访问相册 */
include ':react-native-image-picker'
project(':react-native-image-picker').projectDir = new File(settingsDir, '../node_modules/react-native-image-picker/android')
IOS
cd ios && pod install && cd ..
使用示例:
import { View, Text ,SafeAreaView,Button,Image} from 'react-native'
import React,{useState} from 'react'
import {launchImageLibrary} from 'react-native-image-picker';
export default function App() {
const [imgList, setimgList] = useState([])
const handleClick= async()=>{
launchImageLibrary(
{
mediaType: 'photo',
selectionLimit: 6,
includeBase64: true,
maxWidth: 1000,
maxHeight: 1000,
},
async res => {
const curFiles = res.assets;
let result
for(var i = 0; i < curFiles.length; i++){
console.log(curFiles[i]);
result=curFiles[i]
await setimgList([...imgList,curFiles[i]])
}
}
)
}
return (
<SafeAreaView>
<Button title='点击选择图片' onPress={handleClick}/>
{
imgList.map(item=>{
return(
<Image
key={item.url}
style={{width:200, height:200}}
source={{uri:item.uri}}/>
)
})
}
</SafeAreaView>
)
}
感谢浏览!欢迎点赞