如何在 React JS 中应用全屏限制?

how to apply Full screen striction in react js?

这里我正在开发一个考试系统。我想在启动考试组件时应用全屏。 在做学生时严格保持全屏。当he/she退出全屏时自动调用函数保存考试结果。

全屏显示有一些限制,但我建议您使用 https://github.com/sindresorhus/screenfull.js。它维护得很好,让您更容易支持多种浏览器。

在 React 中你可以这样做:

// import/exports depend on your setup, this is just an example
const screenfull = require('screenfull');

class MyComponent extends React.Component {
  componentDidMount() {
    if (screenfull.isEnabled) {
      screenfull.on('change', () => {
        console.log('Am I fullscreen?', screenfull.isFullscreen ? 'Yes' : 'No');
      });
    }
  }

  // enabling fullscreen has to be done after some user input
  toggleFullScreen = () => {
    if (screenfull.isEnabled) {
      screenfull.toggle();
    }
  }

  render() {
    return (
      <button onClick={this.toggleFullScreen}>Toggle fullscreen</button>
    )
  }
}

LE:

要检测全屏变化,您可以使用 screenfull.on('change') 事件:https://github.com/sindresorhus/screenfull.js#detect-fullscreen-change

在上面的示例中为此添加了代码。