使用 Hooks 折叠 React Sidebar [英] Collapse React Sidebar using Hooks
本文介绍了使用 Hooks 折叠 React Sidebar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要根据屏幕尺寸折叠侧边栏.到目前为止,我的所有尝试都不是很幸运.我想知道是否有人可以通过使用 Hooks 给我一些提示.状态设置为isOpen={true}";当宽度达到 768px 或更低时,我需要将其设为 false.
提前致谢
返回 (<div className=菜单栏"><菜单宽度={210}isOpen={真}无叠加无过渡pageWrapId={page-wrap"}外容器Id={外容器"}customBurgerIcon={false}customCrossIcon={false}禁用自动对焦disableCloseOnEsc>
解决方案
这个自定义钩子使用 Window.matchMedia()
根据传递的查询返回一个布尔值:
const { useMemo, useState, useEffect } = Reactconst useMediaQuery = 查询 =>{const mql = useMemo(() => window.matchMedia(query))const [匹配,setMatch] = useState(mql.matches)useEffect(() => {const 处理程序 = e =>setMatch(e.matches)mql.addListener(处理程序)返回 () =>{mql.removeListener(处理程序)}}, [mql])返回匹配}const 演示 = () =>{const close = useMediaQuery('(max-width: 600px)')返回 (<div className="容器">{关闭 ||<旁边/>}<主/>
)}ReactDOM.render(<演示/>,根)
.container {显示:弹性;高度:75vh;}主要的 {弹性:4;高度:100%;背景:紫色;}在旁边 {弹性:1;高度:100%;背景:黄金;}
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script><div id="root"></div>
I need to collapse my Sidebar base on screen size. So far I was not lucky with all my attempts. I was wondering if someone could give me some tips about that by using Hooks. The status is set to "isOpen={true}" and I need to make it false when reached width 768px or lower.
Thanks in advance
return (
<div className="menu-bar">
<Menu
width={210}
isOpen={true}
noOverlay
noTransition
pageWrapId={"page-wrap"}
outerContainerId={"outer-container"}
customBurgerIcon={false}
customCrossIcon={false}
disableAutoFocus
disableCloseOnEsc
>
解决方案
This custom hook uses Window.matchMedia()
to return a Boolean according to the query passed:
const { useMemo, useState, useEffect } = React
const useMediaQuery = query => {
const mql = useMemo(() => window.matchMedia(query))
const [match, setMatch] = useState(mql.matches)
useEffect(() => {
const handler = e => setMatch(e.matches)
mql.addListener(handler)
return () => {
mql.removeListener(handler)
}
}, [mql])
return match
}
const Demo = () => {
const close = useMediaQuery('(max-width: 600px)')
return (
<div className="container">
{close || <aside />}
<main />
</div>
)
}
ReactDOM.render(
<Demo />,
root
)
.container {
display: flex;
height: 75vh;
}
main {
flex: 4;
height: 100%;
background: purple;
}
aside {
flex: 1;
height: 100%;
background: gold;
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
这篇关于使用 Hooks 折叠 React Sidebar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文