Answer a question

I'm trying to control the play/pause state of a video using ref's in React.js, my code works but there are tslint errors I am trying to work through:

function App() {
    const playVideo = (event:any) => {
        video.current.play()
    }
    const video = useRef(null)

    return (
        <div className="App">
            <video ref={video1} loop src={bike}/>
        </div>
    );
}

This will cause

TS2531: Object is possibly 'null'.

So I try to change const video = useRef(null) to const video = useRef(new HTMLVideoElement())

and I get: TypeError: Illegal constructor

I have also tried: const video = useRef(HTMLVideoElement) which results in:

TS2339: Property 'play' does not exist on type '{ new (): HTMLVideoElement; prototype: HTMLVideoElement; }'

Answers

To set the type for the ref, you set the type like this: useRef<HTMLVideoElement>(). Then, to handle the fact that the object is possibly null (since it's null or undefined before the component is mounted!), you can just check whether it exists.

const App = () => {
  const video = useRef<HTMLVideoElement>();
  const playVideo = (event: any) => {
    video.current && video.current.play();
  };

  return (
    <div className="App">
      <video ref={video} loop src={bike} />
    </div>
  );
};
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐