react 中不使用videojs解决 多个video自带全屏 点击全屏时调用方法
时间: 2023-09-18 21:13:02 浏览: 54
如果你不想使用 video.js 播放器库,你可以使用 React 自带的 `HTMLMediaElement` API 来实现多个 video 自带全屏并在点击全屏时调用方法。以下是一个使用函数组件的示例:
```javascript
import React, { useRef, useState } from 'react';
function VideoPlayer(props) {
const videoRef = useRef(null);
const [isFullScreen, setIsFullScreen] = useState(false);
const handleFullscreenChange = () => {
setIsFullScreen(document.fullscreenElement === videoRef.current);
if (document.fullscreenElement === videoRef.current) {
// 进入全屏模式时调用的方法
} else {
// 退出全屏模式时调用的方法
}
};
const handleClickFullscreen = () => {
if (!isFullScreen) {
videoRef.current.requestFullscreen();
} else {
document.exitFullscreen();
}
};
return (
<div>
<video ref={videoRef} className="video-js vjs-default-skin" controls onFullscreenChange={handleFullscreenChange}>
<source src={props.src} type="video/mp4" />
</video>
<button onClick={handleClickFullscreen}>全屏</button>
</div>
);
}
export default VideoPlayer;
```
在这个示例中,我们使用了 React 的 `useRef` 和 `useState` 钩子来引用 video 元素和跟踪全屏状态。我们在 video 元素上添加了 `onFullscreenChange` 事件监听器,该监听器将在进入或退出全屏模式时触发,并调用 `handleFullscreenChange` 方法。我们还添加了一个按钮来切换全屏模式,并在点击时调用 `handleClickFullscreen` 方法。
为了在应用中使用多个视频播放器,你可以在父组件中渲染多个 `VideoPlayer` 组件。例如:
```javascript
import React from 'react';
import VideoPlayer from './VideoPlayer';
function App() {
return (
<div>
<VideoPlayer src="video1.mp4" />
<VideoPlayer src="video2.mp4" />
</div>
);
}
export default App;
```
这将在应用中渲染两个视频播放器,每个播放器都可以自带全屏,并在进入或退出全屏模式时调用相应的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)