1

私はReactとtypescriptが初めてです。

私がやろうとしているのは、機能的なカメラコンポーネントをレンダリングするクラスコンポーネントがあります。ユーザーが (カメラ コンポーネントから) 画像を保存するときに、その base64 文字列を親コンポーネントで使用したいと考えています。それが理にかなっていることを願っています。

My Class コンポーネント (親)

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

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 に答える