如何解决将数据从子级功能组件传递到父级-React / Typescript
我是React和打字稿的新手。
我正在尝试做的事情: 我有一个类组件,它呈现了一个功能相机组件。 当用户保存图像(来自相机组件)时,我想在父组件中使用该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'。
-谢谢。
解决方法
您将使用传递给孩子的回调。截屏后,您将其称为子级,将数据传递给子级:
class Form extends React.Component<any,any>{
state = { /* ... */ };
handleCapture = base64img => {
// use the base64 string
console.log(base64img);
};
public render() {
<div className="cameraSection">
{this.state.displayCamera && (
<WebcamCapture onCapture={this.handleCapture} />
)}
</div>
}
和
const WebcamCapture = ({onCapture}: any) => {
const webcamRef = useRef(null);
let [imgSrc,setImgSrc] = useState<string | null>(null);
const capture = useCallback(() => {
const base64 = (webcamRef as any).current.getScreenshot();
setImgSrc(base64);
// call the callback
onCapture(base64);
},[setImgSrc,onCapture])
// ...
}
,
在父组件中
// dont forgot to bind this
updateBase64(data){
this.setState(base64: data});
}
render(){
return(
...
<WebcamCapture updateBase64={this.updateBase64}/>);
...
}1
在子组件中
props.updateBase64(base64)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。