[英]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.