[英]how to rerender a page using UseEffect hook on window.innerWidth in react
I want to make some changes depending on the screen size我想根据屏幕大小进行一些更改
useEffect(() => {
console.log("am called");
if (window.innerWidth < 800) {
document.getElementsByTagName("body")[0].style.display = "none";
}
if (window.innerWidth > 800) {
document.getElementsByTagName("body")[0].style.display = "block";
}
}, [window.innerWidth]);
what is the problem with this code这段代码有什么问题
You need to observe window size changing and put this value to state.您需要观察 window 大小的变化,并将此值放入 state。
const [width, setWidth] = useState(0)
useEffect(() => {
const onResize = () => setWidth(window.innerWidth)
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener("resize", onResize)
}
}, [setWidth])
//and then
useEffect(() => {
console.log("am called");
if (width< 800) {
document.getElementsByTagName("body")[0].style.display = "none";
} else {
document.getElementsByTagName("body")[0].style.display = "block";
}
}, [width]);
better solution更好的解决方案
export default function useMatchMedia(condition) {
const [isMatching, setIsMatching] = useState(false);
useEffect(
function updateMatchMedia() {
if (!condition) return setIsMatching(true);
const updateIsMatching = (event) => setIsMatching(event.matches);
const matcher = window.matchMedia(condition);
setIsMatching(matcher.matches);
matcher.addEventListener('change', updateIsMatching);
return () => {
matcher.removeEventListener('change', updateIsMatching);
};
},
[condition]
);
return [isMatching];
}
then you can use it那么你可以使用它
isTablet = useMatchMedia(`(max-width: 800px)`);
useEffect(() => {
if(isTablet){
} else {
}
}, [isTablet])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.