如何将 React cloudinary 与 typescript 结合使用?

问题描述 投票:0回答:1
  1. 我正在使用 TypeScript 和 React 开发一个项目。
  2. 尝试使用react cloudinary上传图像并获取图像的url。
  3. 由于示例代码是js,如果我用tsx创建文件就会出错

这是我想使用的示例代码。 `

    import { createContext, useEffect, useState } from "react";
    
    // Create a context to manage the script loading state
    const CloudinaryScriptContext = createContext();
    
    function CloudinaryUploadWidget({ uwConfig, setPublicId }) {
      const [loaded, setLoaded] = useState(false);
    
      useEffect(() => {
        // Check if the script is already loaded
        if (!loaded) {
          const uwScript = document.getElementById("uw");
          if (!uwScript) {
            // If not loaded, create and load the script
            const script = document.createElement("script");
            script.setAttribute("async", "");
            script.setAttribute("id", "uw");
            script.src = "https://upload-widget.cloudinary.com/global/all.js";
            script.addEventListener("load", () => setLoaded(true));
            document.body.appendChild(script);
          } else {
            // If already loaded, update the state
            setLoaded(true);
          }
        }
      }, [loaded]);
    
      const initializeCloudinaryWidget = () => {
        if (loaded) {
          var myWidget = window.cloudinary.createUploadWidget(
            uwConfig,
            (error, result) => {
              if (!error && result && result.event === "success") {
                console.log("Done! Here is the image info: ", result.info);
                setPublicId(result.info.public_id);
              }
            }
          );
        
          document.getElementById("upload_widget").addEventListener(
            "click",
            function () {
              myWidget.open();
            },
            false
          );
        }
      };
    
      return (
        <CloudinaryScriptContext.Provider value={{ loaded }}>
          <button
            id="upload_widget"
            className="cloudinary-button"
            onClick={initializeCloudinaryWidget}
          >
            Upload
          </button>
        </CloudinaryScriptContext.Provider>
      );
    }
    
    export default CloudinaryUploadWidget;
    export { CloudinaryScriptContext };

` 示例代码链接 => https://cloudinary.com/documentation/react_image_and_video_upload

  1. 由于我不打算修改功能部分,所以我尝试使用any忽略类型。

  2. 我尝试在第 30 行的 var myWidget 中同时使用 const 和 let 而不是 var。

  3. 我想使用此代码而不出现类型错误。

  4. 我想通过将 CloudinaryUploadWidget.js 更改为 CloudinaryUploadWidget.tsx 来使用它。

非常感谢您的帮助。

reactjs typescript cloudinary
1个回答
0
投票

试试这个代码;

import React, { createContext, useEffect, useState } from "react";

// Create a context to manage the script loading state
const CloudinaryScriptContext = createContext<{ loaded: boolean }>({ loaded: false });

interface CloudinaryUploadWidgetProps {
  uwConfig: any; // Adjust the type based on the actual type of uwConfig
  setPublicId: React.Dispatch<React.SetStateAction<string | undefined>>;
}

function CloudinaryUploadWidget({ uwConfig, setPublicId }: CloudinaryUploadWidgetProps) {
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    // Check if the script is already loaded
    if (!loaded) {
      const uwScript = document.getElementById("uw");
      if (!uwScript) {
        // If not loaded, create and load the script
        const script = document.createElement("script");
        script.setAttribute("async", "");
        script.setAttribute("id", "uw");
        script.src = "https://upload-widget.cloudinary.com/global/all.js";
        script.addEventListener("load", () => setLoaded(true));
        document.body.appendChild(script);
      } else {
        // If already loaded, update the state
        setLoaded(true);
      }
    }
  }, [loaded]);

  const initializeCloudinaryWidget = () => {
    if (loaded) {
      const myWidget: any = window.cloudinary.createUploadWidget(
        uwConfig,
        (error: any, result: any) => {
          if (!error && result && result.event === "success") {
            console.log("Done! Here is the image info: ", result.info);
            setPublicId(result.info.public_id);
          }
        }
      );

      document.getElementById("upload_widget")?.addEventListener(
        "click",
        () => {
          myWidget.open();
        },
        false
      );
    }
  };

  return (
    <CloudinaryScriptContext.Provider value={{ loaded }}>
      <button
        id="upload_widget"
        className="cloudinary-button"
        onClick={initializeCloudinaryWidget}
      >
        Upload
      </button>
    </CloudinaryScriptContext.Provider>
  );
}

export default CloudinaryUploadWidget;
export { CloudinaryScriptContext };

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.