问题描述
这可能是一个菜鸟问题,但请相信我,我已经搜寻了我一生,我似乎无法解决或找到解决此问题的资源。
我的问题很简单,我有一个按钮,按下该按钮可从设备打开图像选择器。我还有一个ScrollView,理想情况下,它应该包含我从设备中选取的所有图像。
所以我要做的是:选择一个图像,然后在ScrollView上显示该图像。滚动视图本身可以显示图像 ,只要它们在启动时就可用 ,但是我希望能够在从图库中选取图像时添加图像。
我尝试使用状态对象,但是由于某种原因,scrollview不会更新。
这是相关的选择器代码:
const addAsset = () => {
const options = {
title: title,customButtons: [],storageOptions: {
skipBackup: true,path: '../../assets/imgs',},};
ImagePicker.showImagePicker(options,(response) => {
// console.log('Response = ',response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ',response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ',response.customButton);
alert(response.customButton);
} else {
let oldSource = dataSource;
// oldSource.push(response.uri)
dataSource.push({
id: 4,image: response.uri
})
// setDataSource(oldSource) //update state to update Image
// console.log(dataSource)
}
});
}
最小ImageView对象:
const ImageView = (key,src) => {
return (
// Flat List Item
<View key={src.id} style={{padding: 10}}>
<Image source={src.image}/>
</View>
);
};
然后在ScrollView上尝试:
<ScrollView horizontal style={styles.assetsWrapper}>
{dataSource.map(ItemView)}
</ScrollView>
对于那些想知道的数据源,看起来像这样:
const [dataSource,setDataSource] = useState([]);
解决方法
尝试一下..我保持简单,您可以根据需要进行更改
...
else {
let oldSource = [...dataSource];
dataSource.push(image)
setDataSource(oldSource)
}
//////////
<ScrollView horizontal style={styles.assetsWrapper}>
{dataSource.map((item,index) => (
<ImageView key={index} image={item} />
))}
</ScrollView>
////////
const ImageView = ({image}) => {
return (
// Flat List Item
<View style={{padding: 10}}>
<Image source={image}/>
</View>
);
};