我是 React 和 typescript 的新手。
我想做的事情:我有一个类组件,它呈现一个功能性的相机组件。当用户保存图像(来自相机组件)时,我想在父组件中使用该 base64 字符串。希望这是有道理的。
我的班级组件(父级)
class Form extends React.Component<any, any>{
constructor(props: any) {
super(props);
this.state = { ... }
...
public render() {
<div className="cameraSection">
{this.state.displayCamera &&
<WebcamCapture />
}
</div>
}
我的相机组件:
import * as React from 'react';
import { useEffect, useRef, useState, useCallback } from 'react';
import Webcam from 'react-webcam'
const WebcamCapture = (props: any) => {
const webcamRef = useRef(null);
let [imgSrc, setImgSrc] = useState<string | null>(null);
const capture = useCallback(() => {
const base64 = (webcamRef as any).current.getScreenshot();
setImgSrc(base64);
}, [webcamRef, setImgSrc])
return (
<>
<div className="row">
<Webcam
audio={false}
ref={webcamRef}
screenshotFormat="image/jpeg"
videoConstraints={videoConstraints}
/>
<button onClick={capture}>Take picture</button>
</div>
{imgSrc && (<>
<div className="row">
<img src={imgSrc} />
<div className="col-md-3">
<button onClick={() => {setImgSrc(null)}}>delete</button>
</div>
</div>
</>
)}
</>
);
我是我想从类组件访问的“imgSrc”。
-谢谢。