Inv*_*e_Q 3 javascript typescript reactjs electron
我有以下问题
const imageSrc = webcamRef.current.getScreenshot();
Run Code Online (Sandbox Code Playgroud)
错误:对象可能为“null”;
和 src={imgSrc}
<img src={imgSrc} />
Run Code Online (Sandbox Code Playgroud)
错误:类型“null”不可分配给类型“string |” undefined'.ts(2322) index.d.ts(2053, 9):预期类型来自属性“src”,该属性在类型“DetailedHTMLProps<ImgHTMLAttributes, HTMLImageElement>”上声明
完整代码如下:
import React, { createRef, useRef, useState } from "react";
import Webcam from "react-webcam";
const WebcamCapture = () => {
const webcamRef = useRef(null);
const [imgSrc, setImgSrc] = useState(null);
const capture = React.useCallback(() => {
const imageSrc = webcamRef.current.getScreenshot();
setImgSrc(imageSrc);
}, [webcamRef, setImgSrc]);
return (
<>
<Webcam
audio={false}
ref={webcamRef}
screenshotFormat="image/jpeg"
/>
<button onClick={capture}>Capture photo</button>
{imgSrc && (
<img
src={imgSrc}
/>
)}
</>
);
};
export default WebcamCapture;
Run Code Online (Sandbox Code Playgroud)
这是解决方案:
const webcamRef = useRef<Webcam>(null);
const [imgSrc, setImgSrc] = useState<string | null>(null);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2402 次 |
| 最近记录: |