容器挤压引发的思考
2 min read
Table of Contents
起因
最近在学next的时候发现siderbar收起的时候文字会发生挤压变形的现象,看起来非常不舒服,于是我就想找一个方法来避免这种现象的发生。
解决方法
我们可以通过transition + onTransitionEnd事件来实现一个过渡的效果,从而避免文字挤压变形的问题。下面是一个简单的示例代码:
'use client'import { MenuIcon } from 'lucide-react'import { cn } from '@/lib/utils'import { useState } from 'react'export default function Sidebar() { const [isToogled, setIsToggled] = useState(false) const [isLabelVisible, setIsLabelVisible] = useState(true)
const toogle = () => { setIsToggled((value) => { if (!value) setIsLabelVisible(false) return !value }) }
return ( <aside onTransitionEnd={(event) => { if (event.propertyName === 'width' && !isToogled) setIsLabelVisible(true) }} className={cn( 'hidden shrink-0 overflow-hidden border-r bg-card/80 px-4 py-6 lg:block', !isToogled ? 'w-63' : 'w-16', 'transition-[width] duration-300 ease-in-out' )} > <div className="w-full flex items-center gap-4"> <MenuIcon onClick={toogle} className='cursor-pointer'/> {isLabelVisible && <span className="text-lg whitespace-nowrap">side bar</span>} </div> </aside> )}效果
原理
通过监听宽度变化的过渡结束事件,我们可以在容器收起时先隐藏文字标签,等过渡完成后再显示出来,从而避免了文字挤压变形的问题。这样用户在交互时就不会感受到不适。 这种方法不仅适用于侧边栏的收起效果,还可以应用于其他需要动态调整宽度或高度的容器中,提升整体的用户体验。
评论 (0)
请先登录后再发表评论