reactjs - 通过 GatsbyJS/ReactJS 进行 OrientationChange 的全屏视频(什么是最佳实践?)
问题描述
我正在寻找 GatsbyJS/ReactJS 最佳实践,以添加窗口事件侦听器,以通过移动设备上的 cssorientationchange
全屏查看元素。<video>
目前,我正在通过将<script />
标签与dangerouslySetInnerHTML
. 是<script>
标签和css
实现这一目标的最佳方式吗?
import React from 'react'
const LivePage = () => (
<>
<script
dangerouslySetInnerHTML={{ __html:
`window.addEventListener("orientationchange", function() {
const elem = document.querySelector( 'video' );
if (window.orientation === 90 || window.orientation === -90){
elem.classList.add( 'full' );
} else {
elem.classList.remove( 'full' );
}
})`
}}
/>
<div className="video">
<video src="//myvideo.mp4" />
</div>
<>
)
export default LivePage
关联的 SASS/CSS
video.full
background-color: $black
width: 100vw
height: 100vh
position: absolute
top: 0
left: 0
object-fit: contain
z-index: 50
解决方案
你做错了很多。您可能需要阅读 React 文档并了解数据流(自上而下)、状态和渲染。这是一个示例,说明如何使用带有钩子的 React 16.8+ 来做你想做的事情:
import React, { useState, useEffect } from "react"
const LivePage = () => {
const [fullScreen, setFullScreen] = useState(false)
useEffect(() => {
const listener = () => {
setFullScreen(Math.abs(window.orientation) === 90)
}
window.addEventListener("orientationchange", listener)
return () => {
window.removeEventListener(listener)
}
}, [setFullScreen])
return (
<div className="video">
<video src="//myvideo.mp4" className={fullScreen && "full"} />
</div>
)
}
export default LivePage
或者不使用 React Hooks(例如对于 <16.8 的 React 版本),这实际上是相同的:
import React from "react"
class LivePage extends React.PureComponent {
state = {
fullScreen: false,
}
orientationListener = () => {
this.setState({ fullScreen: Math.abs(window.orientation) === 90 })
}
componentDidMount() {
window.addEventListener("orientationchange", this.orientationListener)
}
componentWillUnmount() {
window.removeEventListener(this.orientationListener)
}
render() {
return (
<div className="video">
<video
src="//myvideo.mp4"
className={this.state.fullScreen && "full"}
/>
</div>
)
}
}
export default LivePage
推荐阅读
- swift - Firestore 对 Orderd By 的无效查询?
- android - 最快的字符串二进制文件 | grep
- styled-components - 将 styled-components 主题对象转换为样式
- python - BlueJeans ApiException:415“不支持的媒体类型”
- rust - 一个二进制文件在断点处停止,另一个没有 - 没有定义断点
- bootstrap-4 - 如何确保图像在 Bootstrap 中以统一大小显示?
- r - 如何在不打印美学错误的情况下将标签子集到 ggplot 图?
- python - 点的聚类采样
- spacy - 批量句子中的 Spacy 火车
- android - 如何将 MethodChannel Result 传递给新的 Activity?