【问题标题】:Using div React useRef hook, typescript?使用 div React useRef 钩子,打字稿?
【发布时间】:2022-01-08 01:36:21
【问题描述】:

我正在使用 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>'

基本上它所要做的就是下载已经生成的二维码。

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    尝试初始化它:

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

    【讨论】:

    • 成功了,谢谢
    • 不错!那你能接受答案吗? ;)
    猜你喜欢
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2020-09-17
    • 2019-10-28
    • 2020-11-19
    • 1970-01-01
    相关资源
    最近更新 更多