Full screen display

Sometimes you need to click on an image to go to full screen, so use the requestFullScreen event to do this

Note: requestFullScreen events only work on elements

Code implementation

Encapsulate custom hooks

import React, { useRef } from 'react' export const UseScreenFull = () => { const eleScreenFullRef = useRef(null) const isFullScreen = useRef(false) const entryFullScreen = (element:any) => { if (element.requestFullscreen) { element.requestFullscreen(); } else if (element mozRequestFullScreen) {/ / compatible with firefox element mozRequestFullScreen (); } else if (element. WebkitRequestFullscreen) {/ / element compatible with Google. WebkitRequestFullscreen (); } else if (element. MsRequestFullscreen) {/ / compatible element. IE msRequestFullscreen (); }} const exitFullscreen = () => {if (document.exitFullscreen) {document.exitFullscreen()}} Entry and exit trigger the document. The addEventListener (' fullscreenchange ', () => { if (isFullScreen.current) { isFullScreen.current = false } else { isFullScreen.current = true } }) const showFullSize = () => { const element = eleScreenFullRef.current; entryFullScreen(element) } const exitFullSize = () => { if (isFullScreen.current) { exitFullscreen() } } const clickSelfOpen = () => { if (isFullScreen.current) { exitFullSize() } else { showFullSize() } } return { // Exit the full-screen event showFullSize, // enter the full-screen event clickSelfOpen, // Click yourself to enter the full-screen event or exit the full-screen event}}Copy the code

use

A custom hook is introduced to bind eleScreenFullRef to the ref that you want to implement full-screen

 const { 
   eleScreenFullRef,
   exitFullSize,
   showFullSize,
   clickSelfOpen } = UseScreenFull();

<img ref={eleScreenFullRef} onClick={clickSelfOpen} src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/83d888e2e61444d9952103e5cb3287e0~tplv-k3u1fbpfcp-zoom-1.image"/>`
Copy the code