简体   繁体   中英

Multiple video element pointing to the same useRef() [React]

Is it possible to use the same videoRef on 2 elements?

Intended outcome: displaying 2 videos in 2 different <video> , pointing to the same videoRef on the same page concurrently.

const videoRef = useRef();
const videoRef2 = useRef();

return (
  <div>
    {/* ... a video (videoRef) at top */}
    <video
      videoRef={videoRef}
    />
    {/* ... somehere else on the same page, the same video (videoRef) */}
    <video
      videoRef={videoRef}
    />
    {/* ... another video (videoRef2) */}
    <video
      videoRef={videoRef2}
    />
  </div>
);

I'm not sure that is a possible thing to do but there's a good way to handle this

const videoRefs = useRef([React.createRef(), React.createRef()]);

<video
   ref={videoRefs.current[0]}
/>
....
<video
   ref={videoRefs.current[1]}
/>

Or may be as this :

const videoRefs = useRef([]);

<video
  ref = {el => videoRefs.current[0] = el}
/>
....
<video
  ref = {el => videoRefs.current[1] = el}
/>

check this out too

  • No. You can't use a reference to 2 elements because each element which is rendered in the real DOM is unique. videoRef will refer to second <video>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM