React Native HOC component



我正在尝试做一个带有缓存HoC组件,但遇到了一些问题...

这就是 HoC:

// HOC for cached images
const withCache = (Component) => {
const Wrapped = (props) => {
console.log(props);
const [uri, setUri] = useState(null);
useEffect(() => {
(async () => {
const { uri } = props;
const name = shorthash.unique(uri);
const path = `${FileSystem.cacheDirectory}${name}`;
const image = await FileSystem.getInfoAsync(path);
if (image.exists) {
console.log("Read image from cache");
setUri(image.uri);
return;
} else {
console.log("Downloading image to cache");
const newImage = await FileSystem.downloadAsync(uri, path);
setUri(newImage.uri);
}
})();
}, []);
return <Component {...props} uri={uri} />;
};
Wrapped.propTypes = Component.propTypes;
return Wrapped;
};
export default withCache;

问题是"组件"是一个具有特定 propType 和 defaultProps 的自定义图像组件。

如何使用此组件?我试过:

const CachedImage = withCache(<MyCustomImage uri={"https://..."} height={100} ripple />)
...
return (<CachedImage />)

但不能:(工作我想要的是将布尔属性传递给名为"cached"的自定义图像组件,如果为 true,则返回包装在 HOC 中的自定义图像组件

为了使用 HOC,您需要在功能组件之外创建实例,例如

const CachedImage = withCache(MyCustomImage)

并像使用它一样使用

const MyComp = () => {
...
return (<CachedImage  uri={"https://..."} height={100} ripple />)
}

HoC 的最终实现,以防将来有人发现它有用。

import React, { useState, useEffect } from "react";
import shorthash from "shorthash";
import * as FileSystem from "expo-file-system";
// HOC for cached images
const withCache = (Component) => {
const Wrapped = (props) => {
console.log(props);
const [uri, setUri] = useState(null);
useEffect(() => {
(async () => {
const { uri } = props;
const name = shorthash.unique(uri);
const path = `${FileSystem.cacheDirectory}${name}`;
const image = await FileSystem.getInfoAsync(path);
if (image.exists) {
console.log("Read image from cache");
setUri(image.uri);
return;
} else {
console.log("Downloading image to cache");
const newImage = await FileSystem.downloadAsync(uri, path);
setUri(newImage.uri);
}
})();
}, []);
// Needs to have the final uri before render the image
return uri && <Component {...props} uri={uri} />;
};
Wrapped.propTypes = Component.propTypes;
return Wrapped;
};
export default withCache;

相关内容

  • 没有找到相关文章

最新更新