【问题标题】:How create a custom React hook and combine the logic from my (helper) functions如何创建自定义 React 挂钩并结合我的(辅助)函数的逻辑
【发布时间】:2023-01-24 19:49:26
【问题描述】:

我在下面创建了两个函数,以添加消除我的 React 应用程序中的外部 src 和 <script> 标签:

type Args = {
    src: string;
    id: string;
    onLoad?: () => void;
  };

  const addScript = ({ src, id, onLoad }: Args) => {
    const existing = document.getElementById(id);
    if (existing) {
      return existing;
    }
    const script = document.createElement('script');
    script.src = src;
    script.id = id;
    script.async = true;
    script.onload = () => {
      if (onLoad) {
        onLoad();
      }
    };
    document.body.appendChild(script);
    return script;
  };

  const removeScript = ({ id }: { id: string }) => {
    const script = document.getElementById(id);
    if (script) {
      document.body.removeChild(script);
    }
  };

然后我可以像这样使用它:

useEffect(() => {
    const script = addScript({
      src: `https://domain/js/main.js`,
      id: 'ad-script',
      onLoad: () => {
        console.log('Script loaded!');
      },
    });
    return () => removeScript({ id: script.id });
  }, [id]);

因为我在这里使用 useEffect 钩子。如何创建返回上述逻辑的自定义 React 钩子,我可以像这样使用:useScript('https://domain/js/main.js', 'my-script' );

【问题讨论】:

    标签: reactjs react-hooks react-custom-hooks


    【解决方案1】:

    自定义挂钩获取 addScript 所需的相同参数。它将 onLoad 存储在 ref 中,因此如果 onLoad 发生变化,useEffect 将不会触发。这使您无需使用 useCallback 包装 onLoad

    const useScript = ({ src, id, onLoad }: Args) => {
      const onLoadRef = useRef(onLoad);
    
      useEffect(() => {
        const script = addScript({ src, id, onLoad: onLoadRef.current?.() });
        
        return () => removeScript({ id: script.id });
      }, [src, id]);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-02
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2020-05-28
      • 2022-09-27
      • 2016-04-25
      • 2023-01-18
      相关资源
      最近更新 更多