Updating source URL on HTML5 video with React

前端 未结 2 810
孤街浪徒
孤街浪徒 2020-12-29 20:40

I want to update the source tag in a HTML5 video element so that when I click a button, whatever\'s playing switches to a new video.

I have a Clip component that ret

相关标签:
2条回答
  • 2020-12-29 20:46

    Short awnser: Add a key prop to <Clip> or <video>, e.g.:

    function Clip({ url }) {
      return (
        <video key={url}>
          <source src={url} />
        </video>
      );
    }
    

    Long awnser: The video won't change because in essence you're only modifying the <source> element and React understands that <video> should remain unchanged, so it does not update it on the DOM and doesn't trigger a new load event for that source.

    To make sure not only <source> gets updated but also <video>, add a key prop to it so React understands that's a whole new element.

    For a more complete explanation, check out this article about keys on React docs :)

    0 讨论(0)
  • 2020-12-29 21:02

    Changing the src of <source /> doesn't seem to switch the video for some reason. This isn't a react issue I don't think. Probably just how <source /> works. Maybe you have to call .load() on the element again. But it's just easier to set it directly on the element itself.

    See the comment to the top answer: Can I use javascript to dynamically change a video's source?

    You can set src directly on element instead:

    function Clip(props) {
      return (
        <video width="320" height="240" src={props.url} controls autoPlay>
        </video>
      )
    }
    
    0 讨论(0)
提交回复
热议问题