electron React-Webcam:如何解决“对象可能为'null'”和“类型'null'不可赋值给类型'string'”|不确定"

ejk8hzay  于 2023-09-28  发布在  Electron
关注(0)|答案(2)|浏览(147)

我有问题

const imageSrc = webcamRef.current.getScreenshot();

错误:对象可能为“null”;
且src={imgSrc}

<img src={imgSrc} />

错误:类型“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;
ghg1uchk

ghg1uchk1#

解决方案如下:

const webcamRef = useRef<Webcam>(null);
 const [imgSrc, setImgSrc] = useState<string | null>(null);
4xrmg8kj

4xrmg8kj2#

即使添加了上面的行,它也不适合我。
检查current null或not对我有效。

if (webcamRef.current) {
  const imageSrc = webcamRef.current.getScreenshot();
  setImgSrc(imageSrc);
}

相关问题