如何使用 Reactjs 启用全屏模式?

How to enable implement fullscreen mode with Reactjs?

有没有办法在 React 组件函数中实现全屏 API?

我可以推荐你这个包react-full-screen

您可以参考@chiragrupani/fullscreen-react包。它同时支持 class 组件和 hooks/function 组件。同时,它支持允许多个元素进入全屏。它的用法很简单:

安装:npm i @chiragrupani/fullscreen-react

  1. 添加触发全屏的button/icon。您也可以让它在进入和退出全屏之间切换。
<button onClick={e => this.setState({isFullScreen: true})}>Go Fullscreen</button>
  1. 用npm包提供的FullScreen Component包裹你要进入全屏的元素如下图:
    <FullScreen
        isFullScreen={this.state.isFullScreen}
        onChange={(isFullScreen) => {
            this.setState({ isFullScreen });
        }}
        >
        <div>Fullscreen</div>
    </FullScreen>

对于钩子,代码类似:

export default function FSExampleHook() {
  let [isFullScreen, setFullScreen] = React.useState(false);

  return (
    <>
      <button onClick={(e) => setFullScreen(true)}>Go Fullscreen</button>

      <FullScreen
        isFullScreen={isFullScreen}
        onChange={(isFull: boolean) => {
          setFullScreen(isFull);
        }}
      >
        <div>Fullscreen</div>
      </FullScreen>
    </>
  );
}

PS: 我不是这个库的作者,但我在我的生产站点中使用它。