簡體   English   中英

使用 div React useRef 鈎子,typescript?

[英]Using div React useRef hook, typescript?

我正在使用 qrcode.react 庫並創建 useRef 掛鈎

const qrRef = React.useRef();

然后在

const downloadQRCode = (evt: React.FormEvent) =>{
        evt.preventDefault();

        // @ts-ignore
        let canvas = qrRef.current.querySelector("canvas");
        let image = canvas.toDataURL("image/png");
        let anchor = document.createElement("a");
        anchor.href = image;
        anchor.download="qr-code.png";
        document.body.appendChild(anchor);
        anchor.click();
        document.body.removeChild(anchor);
        
        setUrl("");
    };
<div className="qr-container">
    <form onSubmit={downloadQRCode} className="qr-container_form">
       <input
         type="text"
         value={url}
         onChange={(e) => setUrl(e.target.value)}
         placeholder="https://example.com"
       />
       <button type="submit">Download QR Code</button>
    </form>
    <div className="qr-container_qr-code" ref={qrRef}>{qrCode}</div>
</div>

我收到了這個錯誤

Type 'MutableRefObject<undefined>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
  Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
    Types of property 'current' are incompatible.
      Type 'undefined' is not assignable to type 'HTMLDivElement | null'.ts(2322)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

基本上它所要做的就是下載已經生成的二維碼。

嘗試初始化它:

const qrRef = React.useRef<HTMLDivElement>(null);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM