gpt4 book ai didi

javascript - react JS : ability to detect switching tab in browser

转载 作者:行者123 更新时间:2023-11-30 11:13:15 31 4
gpt4 key购买 nike

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

在 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;

最佳答案

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')
);

关于javascript - react JS : ability to detect switching tab in browser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52744866/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com