gpt4 book ai didi

reactjs - 使用 div React useRef 钩子(Hook), typescript ?

转载 作者:行者123 更新时间:2023-12-05 09:29:57 24 4
gpt4 key购买 nike

我正在使用 qrcode.react 库并创建 useRef 钩子(Hook)

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);

关于reactjs - 使用 div React useRef 钩子(Hook), typescript ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70184583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com