may*_*han 3 image react-native
我想这样使用图像:
<Image
source={{
uri: 'https://facebook.github.io/react/logo-og.png',
method: 'POST',
headers: {
Pragma: 'no-cache',
},
body: '...',
}}
style={{width: 400, height: 400}}
/>
Run Code Online (Sandbox Code Playgroud)
但我希望如果图像失败,它将尝试再次重新加载。
我们在 React Native 上有这个选项吗?我知道该onError功能,但我不知道如何使图像再次重新加载。
谢谢。
@mindmaster的解决方案并不实用,请尝试在每次重试时为图像传递不同的密钥以重新渲染组件Image。
使用 Hooks 就更容易了:
const MyComponent = () => {
const [retryCounter, setRetryCounter] = useState(0);
const onImageLoaded = useCallback(() => {
console.log('Image loaded!');
}, []);
const onImageError = useCallback(() => {
Alert.alert('Error', "Can't load the image!", [
{
text: 'Cancel',
style: 'cancel',
},
{
text: 'Retry',
onPress: setRetryCounter((prevCounter) => prevCounter + 1),
},
]);
}, []);
return (
<View>
<Image
key={`image-${retryCounter}`}
source={{
uri: 'https://facebook.github.io/react/logo-og.png',
method: 'POST',
headers: {
Pragma: 'no-cache',
},
body: '...',
}}
style={{ width: 400, height: 400 }}
onLoad={onImageLoaded}
onError={onImageError}
/>
</View>
);
};
Run Code Online (Sandbox Code Playgroud)