首页 > 解决方案 > 通过 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

标签: reactjsgatsby

解决方案


你做错了很多。您可能需要阅读 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

推荐阅读