如何使用React Hooks为Ref元素添加onClick事件?

时间:2019-07-27 12:09:07

标签: reactjs video-reactjs

我要切换全屏。组件具有toggleFullscreen方法,但在文档中仅是类组件。

import React, { useRef } from 'react';

// Components
import { Player } from 'video-react';

export default () => {
const videoRef = useRef(null);

return (
  <div>
   <Player ref={videoRef} 
   src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4" />
  </div>
 );
};

2 个答案:

答案 0 :(得分:0)

如果要在安装组件后立即切换到全屏,可以使用https://ci3.googleusercontent.com/proxy/my5xZQ0qLzgUUNW2RuvcbI6uWTmEfE8Cibdg6ErAEwmrnujaOsun-cGKac_Q9dp_67Ocl03NaR8NCpmB=s0-d-e1-ft#http://dummyhost.dummy/test.png?id=xxx 来调用该功能

useEffect

重要的部分是export default () => { ... React.useEffect(() => { videoRef.current.toggleFullscreen() // toggle back to normal mode when the component unmounts (optional) return () => { videoRef.current.toggleFullscreen() } }, []) return ( ... ) } 作为第二个参数。使用此开关时,仅在安装组件时调用一次切换,而不是在每次重新渲染时调用一次。

答案 1 :(得分:0)

import React, { useRef } from 'react';

// Components
import { Player, BigPlayButton } from 'video-react';

export default () => {
const videoRef = useRef(null);
const toggleFullScrn = () => videoRef.current.actions.toggleFullscreen();

return (
<div onClick={toggleFullScrn}>
  <Player ref={videoRef} 
  src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4">
    <BigPlayButton />
  </Player>
</div>

); };