React JS:能够在浏览器中检测切换选项卡

时间:2018-10-10 16:28:28

标签: javascript html reactjs

很抱歉,如果我重复了这个问题,但没有找到解决问题的办法。

React中检测浏览器中的切换选项卡或隐藏浏览器窗口的最佳方法是什么?

我知道有一个Page visibility API,但是我该如何在React组件中实现它呢?

这是最简单的方法,但我不知道是正确的

import React, { Component } from 'react';

class Sample extends Component {
  handleBlur = () => {
    console.log('Blur');
  }

  handleFocus = () => {
    console.log('Focus');
  }

  render() {
    return (
      <div
        style={{ width: 400, height: 200 }}
        onBlur={this.handleBlur}
        onFocus={this.handleFocus}
      >
      test
      </div>
    );
  }
}

export default Sample;

1 个答案:

答案 0 :(得分:3)

let hidden = null;
let visibilityChange = null;
if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support 
  hidden = 'hidden';
  visibilityChange = 'visibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
  hidden = 'msHidden';
  visibilityChange = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
  hidden = 'webkitHidden';
  visibilityChange = 'webkitvisibilitychange';
}

class Hello extends React.Component {

  state = {
    actions: []
  }

  componentDidMount() {
    document.addEventListener(visibilityChange, this.handleVisibilityChange, false);
  }

  handleVisibilityChange = () => {
    if (document[hidden]) {
     this.setState({actions: [...this.state.actions, 'hide']});
    } else {
     this.setState({actions: [...this.state.actions, 'show']});
    }
  }

  componentWillUnmount()    {
    document.removeEventListener(visibilityChange, this.handleVisibilityChange);
  }

  render() {
    return (
      <ul>
      {
        this.state.actions.map((item, key) => <li key={key}>{item}</li>)
      }
    </ul>
    )
  }
}

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);