如何更改react组件中的CSS高度



我使用以下JavaScript代码在0高度和X高度之间切换。这是汉堡图标的下拉菜单。

// Hamburger navigation
const menuToggle = document.querySelector(".menu-toggle");
const nav = menuToggle.parentElement;
const menuDropdown = document.querySelector(".menu-dropdown");
menuToggle.addEventListener("click", event => {
event.preventDefault();
nav.classList.toggle("is-open");
const height = menuDropdown.scrollHeight;
if (nav.classList.contains("is-open")) {
menuDropdown.style.setProperty("height", height + "px");
} else {
menuDropdown.style.setProperty("height", "0");
}
});

我可以在React中使用类似的东西来切换类"是打开的",它很有效:

const [isOpen, setState] = useState(false)
const toggleNav = () => setState(!isOpen)

但是我该如何处理高度呢?

const height = menuDropdown.scrollHeight;
if (nav.classList.contains("is-open")) {
menuDropdown.style.setProperty("height", height + "px");
} else {
menuDropdown.style.setProperty("height", "0");
}

如果有任何建议,我将不胜感激。

使用带有反括号{}的样式属性

import React, { useState } from 'react';
import './Header.scss';
const Header = () => {
const [Height, setHeight] = useState('0px');
const handleClickMenu = () => ((Height == '0px') ? setHeight('80px') : 
setHeight('0px'));
return (
<nav>
<button 
type='button' 
onClick={handleClickMenu} 
className='your-navbar-burger-class'
>
your-hamburger-button
</button>
<div 
className='your-dropdown-menu-class'
style={{ height: Height}}
>
//your dropdown
</div>
</nav>
);
};
export default Header;

您可以使用useEffect来管理高度。

useEffect(()=>{
// your code mere below is just an example.
if (nav.classList.contains("is-open")) {
menuDropdown.style.setProperty("height", height + "px");
} else {
menuDropdown.style.setProperty("height", "0");
}
// [isOpen] here maintain this useEffect and runs only if the value isOpen is changed
}, [isOpen])

useEffect

如果你试图转换下拉菜单的高度,你最好在菜单上切换一个类,并使用纯CSS技术。我推荐"技巧1:最大高度"详细介绍如下:

https://css-tricks.com/using-css-transitions-auto-dimensions/

最新更新