检查浏览器选项卡是否在 ReactJS 中处于焦点 [英] Check if the browser tab is in focus in ReactJS

查看:34
本文介绍了检查浏览器选项卡是否在 ReactJS 中处于焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ReactJS 中有一个网站.每当我的选项卡成为焦点或隐藏时,我都想获得回调.我为此遇到了页面可见性 API,但我不知道如何在 ReactJS 中使用它.

I have a website in ReactJS. I want to get a callback whenever my tab comes in focus or is hidden. I came across the Page Visibility API for this but I'm not able to figure out how to use it in ReactJS.

我应该在哪个生命周期方法中为此注册回调?

In which lifecycle method do I register the callback for this?

推荐答案

这应该有效:

componentDidMount() {
    window.addEventListener("focus", this.onFocus)
}

componentWillUnmount() {
    window.removeEventListener("focus", this.onFocus)
}

onFocus = () => {
    //
}

同样适用于模糊";它应该在选项卡隐藏时起作用.

same goes for "blur" and it should work for when the tab becomes hidden.

检查@Assaf 的答案是否使用钩子.

Check @Assaf's answer for usage with hooks.

这篇关于检查浏览器选项卡是否在 ReactJS 中处于焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆