我正在寻求GatsbyJS / ReactJS最佳实践,它添加了一个orientationchange
窗口事件监听器,以通过移动设备上的CSS来全屏查看<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
答案 0 :(得分:1)
您做错了很多。您可能需要阅读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(例如对于React版本<16.8),实际上是相同的:
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