繁体   English   中英

React Native HOC 组件

[英]React Native HOC component

我正在尝试做一个 withCache 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;

问题是“组件”是具有特定 propTypes 和 defaultProps 的自定义 Image 组件。

我如何使用这个组件? 我努力了:

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

...

return (<CachedImage />)

但不工作:(我想要的是将 boolean 道具传递给名为“缓存”的自定义图像组件,如果为真则返回包装在 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM