最近做react项目碰到个需求:将内容区域全屏现实
浏览器为谷歌浏览器
核心api:
- useRef() // 类似于React.createRef()
- el.webkitRequestFullScreen() // 全屏
废话少说,直接上代码:
import React, { useRef, useEffect } from 'react'
import { Layout, Breadcrumb, message } from 'antd'
import style from './index.less'
export default function Home() {
const contentRef: any = useRef() // 创建ref对象,下面jsx中的ref={contentRef}就是在给这个ref对象赋值,值为被ref附着的dom对象,也就是class="content"的那个div
useEffect(() => {
message.info('按F11可进入全屏')
document.addEventListener('keydown', function (e) {
contentRef.current.focus()
if (e && e.key == 'F11') {
contentRef.current.style.padding = '24px'
contentRef.current.style.margin = '0px'
//捕捉F11键盘动作
e.preventDefault(); //阻止F11默认动作
var el = contentRef.current
var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;//定义不同浏览器的全屏API
//执行全屏
if (typeof rfs != "undefined" && rfs) {
rfs.call(el);
} else if (typeof window.ActiveXObject != "undefined") {
var wscript = new ActiveXObject("WScript.Shell");
if (wscript != null) {
wscript.SendKeys("{F11}");
}
}
}
})
}, []) // 空数组表示副作用只在组件componentDidMount生命周期会执行一次
return (
<>
<Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>首页</Breadcrumb.Item>
</Breadcrumb>
<Content className={style['site-layout-background']} style={{ padding: 24, margin: 0, minHeight: 280, }}>
<div className={style.content} ref={contentRef}>
......
</div>
</Content>
</>
)
}