我正在使用 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>'
基本上它所要做的就是下載已生成的二維碼。
uj5u.com熱心網友回復:
嘗試初始化它:
const qrRef = React.useRef<HTMLDivElement>(null);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370692.html
