我正在使用:Tailwindcss、React 和 Next.js 进行业余项目。
我正在尝试创建一个响应式导航栏,当屏幕尺寸达到顺风定义的“sm”尺寸时,它会显示一个汉堡菜单。
当我单击汉堡包图标时,我希望菜单从高度 0 过渡到 max-h-40。
我觉得我在下面的代码中遗漏了一些微不足道的东西,希望其他人看到这个可以看到我遗漏了什么?
navbar.tsx
"use client"; import Image from "next/image"; import Link from "next/link"; import { useState } from "react"; import logo from "../public/finallang_favicon.ico"; export default function Navbar() { const [showMenu, setShowMenu] = useState(false); const toggleMenu = () => { setShowMenu(!showMenu); }; return ( < div > < nav className = "flex items-center justify-between flex-grow w-auto py-3 text-center border-b px-9 sm:w-auto" > < div className = "flex items-center justify-center flex-shrink-0 sm:mr-6" > < Link href = "/" > < Image src = { logo } alt = "Logo" width = { 48 } height = { 48 } /> < /Link> < /div> < div className = "hidden text-sm sm:block" > < Link href = "#" className = "block mt-4 sm:mr-4 text-slate-900 hover:text-slate-700 sm:mt-0 sm:inline-block" > About < /Link> < Link href = "#" className = "block mt-4 sm:mr-4 text-slate-900 hover:text-slate-700 sm:mt-0 sm:inline-block" > Blog < /Link> < Link href = "#" className = "block mt-4 text-slate-900 hover:text-slate-700 sm:mt-0 sm:inline-block" > Contact Me < /Link> < /div> < div > < button className = "hidden px-4 py-2 text-sm leading-none rounded text-slate-100 hover:text-white sm:inline-block bg-brand" > Download < /button> < button onClick = { toggleMenu } aria - label = "Toggle navigation menu" className = "text-gray-400 align-middle sm:hidden hover:text-gray-900 focus:ring-2 rounded-md" > < svg xmlns = "http://www.w3.org/2000/svg" fill = "none" viewBox = "0 0 24 24" strokeWidth = { 2 } stroke = "currentColor" className = "w-6 h-6" > < path strokeLinecap = "round" strokeLinejoin = "round" d = "M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" / > < /svg> < /button> < /div> < /nav> { showMenu && < div className = { `${showMenu ? "max-h-40" : "h-0"} text-sm text-center sm:hidden transition-all duration-500 ease-in-out overflow-hidden` } > < Link href = "/about" className = "block mt-4 text-slate-900 hover:text-slate-700" > About < /Link> < Link href = "/blog" className = "block mt-4 text-slate-900 hover:text-slate-700" > Blog < /Link> < Link href = "/contact" className = "block mt-4 text-slate-900 hover:text-slate-700" > Contact Me < /Link> < /div> } < /div> ); }
我尝试过的事情:
height: "height"
作为 transitionProperty
添加到我的 tailwind.config.jsoverflow-hidden
类名添加到我的菜单类中transition-all
和 transition-[height]
之间切换当前行为: 当前行为的动图
我期望发生什么:
P粉2168079242024-02-18 10:08:48
通过代码片段进行条件渲染:
{showMenu &&表示元素被挂载到 DOM 中或挂载到 DOM 之外。过渡不会在元素安装/卸载的同一帧上播放。
CSS 属性转换
此外,您还可以使用菜单容器的条件类更改不同的 CSS 属性:
${showMenu ? "max-h-40" : "h-0"}
max-h-40
对应max-height: 10rem
而h-0
对应height: 0
。这意味着我们要更改两个值的初始值:max-height
和height
。根据 MDN,max-height
的初始值为none
和height
的初始值为auto
< /a>.这些值相对于showMenu
的变化如下:
showMenu
true
false
max-height
10rem
none
height
auto
0
回复0取消