将数据从子级功能组件传递到父级-React / Typescript

时间:2020-10-12 13:30:32

标签: reactjs typescript camera usecallback

我是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'。

-谢谢。

2 个答案:

答案 0 :(得分:2)

您将使用传递给孩子的回调。截屏后,您将其称为子级,将数据传递给子级:

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

  // ...
}

答案 1 :(得分:1)

在父组件中

// dont forgot to bind this
updateBase64(data){
    this.setState(base64: data});
}

render(){
 return(
   ...
   <WebcamCapture updateBase64={this.updateBase64}/>);
   ...
}1

在子组件中

props.updateBase64(base64)
相关问题