I have two sibling components WebcamStream
and CaptureArea
, I want to pass reference to WebcamStream
as prop of CaptureArea
, but when I do this, it always null. How to fix this ?
class AppContent extends React.Component {
constructor(props) {
super(props);
this.videoTag = React.createRef();
}
render() {
return (
<div id="content">
<WebcamStream ref={this.videoTag}
width="300" height="300"
title="Real-time video stream from webcam"
id="video" />
<CaptureArea x="20" y="20" width="120"
height="120" color="white"
videoTag={this.videoTag.current}/>
</div>
);
}
}
Why I need this: CaptureArea
generates temporary canvas on current video
tag to get imageData from it. I use imageData to parse QR Code.
ref
is a prop used by React internally much like the key
prop, so you can name it something else and treat it like any other prop in the WebcamStream
component.
innerRef
is a common name for a custom ref that you attach to any of the elements in the component.
Example
function WebcamStream(props) { return <div ref={props.innerRef}> WebcamStream </div>; } class CaptureArea extends React.Component { componentDidMount() { console.log(this.props.videoTag.current); } render() { return <div> CaptureArea </div>; } } class AppContent extends React.Component { videoTag = React.createRef(); render() { return ( <div id="content"> <WebcamStream innerRef={this.videoTag} width="300" height="300" title="Real-time video stream from webcam" id="video" /> <CaptureArea x="20" y="20" width="120" height="120" color="white" videoTag={this.videoTag} /> </div> ); } } ReactDOM.render(<AppContent />, document.getElementById("root"));
<script src="https://unpkg.com/react@16.6.1/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16.6.1/umd/react-dom.production.min.js"></script> <div id="root"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.