export function UsePageVisibility() {
const [isVisible, setIsVisible] = React.useState(getIsDocumentHidden());
console.log(isVisible);
const onVisibilityChange = () => setIsVisible(getIsDocumentHidden());
React.useEffect(() => {
const visibilityChange = getBrowserVisibilityProp();
window.addEventListener(visibilityChange, onVisibilityChange, false);
return () => {
window.removeEventListener(visibilityChange, onVisibilityChange);
};
}, []);
return isVisible;
}
Test.js :
import React, { useState } from "react";
import "./App.css";
import Component from "./component";
export function getBrowserVisibilityProp() {
if (typeof document.hidden !== "undefined") {
// Opera 12.10 and Firefox 18 and later support
return "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
return "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
return "webkitvisibilitychange";
}
}
export function getBrowserDocumentHiddenProp() {
if (typeof document.hidden !== "undefined") {
return "hidden";
} else if (typeof document.msHidden !== "undefined") {
return "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
return "webkitHidden";
}
}
export function getIsDocumentHidden() {
return !document[getBrowserDocumentHiddenProp()];
}
export function UsePageVisibility() {
const [isVisible, setIsVisible] = React.useState(getIsDocumentHidden());
const [counter , setcounter] = useState(false);
console.log(isVisible);
const onVisibilityChange = () => setIsVisible(getIsDocumentHidden());
React.useEffect(() => {
const visibilityChange = getBrowserVisibilityProp();
window.addEventListener(visibilityChange, onVisibilityChange, false);
return () => {
window.removeEventListener(visibilityChange, onVisibilityChange);
};
}, []);
if (!isVisible) {
setcounter(true);
} else {
setcounter(false);
}
return isVisible;
}
App.js :
import React from "react";
import "./App.css";
import { UsePageVisibility } from "./test";
class App extends React.Component {
render() {
return <UsePageVisibility />;
}
}
export default App;
答案 0 :(得分:0)
一旦安装了组件,就会有一个函数自行调用。
尝试:
const onVisibilityChange = () => setIsVisible(() => getIsDocumentHidden());