[英]React - How to change state using media queries
I want to know how can I change the state of a class using media queries?我想知道如何使用媒体查询更改 class 的 state ? For example, the initial state of my state is false, how can I change to true when the screen is higher than 900px
比如我的state的初始state是false,屏幕高于900px怎么改成true
You can add an event listener to a useEffect
hook update your state accordingly.您可以将事件侦听器添加到
useEffect
挂钩,相应地更新您的 state。 For example:例如:
import * as React from "react";
export default function App() {
const [isGreaterThan900px, setIsGreaterThan900px] = React.useState(false);
React.useEffect(() => {
function handleResize() {
if (window.innerWidth > 900) {
setIsGreaterThan900px(true);
} else {
setIsGreaterThan900px(false);
}
}
handleResize();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return (
<div className="App">
<h1>is greater than 900 px: {isGreaterThan900px ? "true" : "false"}</h1>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.