1

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

-谢谢。

4

2 回答 2

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

  // ...
}
于 2020-10-12T13:40:52.410 回答
1

在父组件中

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

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

在子组件中

props.updateBase64(base64)
于 2020-10-12T13:52:56.813 回答