ReactNative:如何在收到新数据时更新ScrollView内容



这可能是一个棘手的问题,但相信我,我已经到处找了,我的一生似乎都无法解决或找到资源来解决这个问题。

我的问题很简单,我有一个按钮,当按下时,会从设备中打开图像选择器。我还有一个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)
}
});
}

最小图像视图对象:

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>

对于那些好奇的人来说,dataSource看起来是这样的:

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>
);
};

最新更新