React自定义三线汉堡下拉组件:如何切换子元素active类
No need for jQuery here—React's state system makes this straightforward. Let's walk through how to handle the active class toggle for your three-line hamburger component:
Step 1: Use React State to Track Toggle State
First, we'll use the useState hook to keep track of whether the menu is active. This state will drive all our UI changes.
Step 2: Create a Click Handler to Toggle State
We'll write a simple function that flips the state value when the button is clicked.
Step 3: Conditionally Apply the active Class
For each of the three span elements, we'll check the current state and add the active class only when the state is true.
Full Component Example
import { useState } from 'react'; const HamburgerMenu = () => { // State to track if the menu is active const [isActive, setIsActive] = useState(false); // Handler to toggle the active state const handleToggle = () => { setIsActive(prevState => !prevState); }; return ( <button onClick={handleToggle} className="hamburger-btn"> <span className="hamburger-lines"> {/* Conditionally add 'active' class based on state */} <span className={`line ${isActive ? 'active' : ''}`}></span> <span className={`line ${isActive ? 'active' : ''}`}></span> <span className={`line ${isActive ? 'active' : ''}`}></span> </span> </button> ); }; export default HamburgerMenu;
A Quick Note on Why This Works
Instead of using jQuery to directly manipulate the DOM (like adding/removing classes), we're letting React's state manage the UI. When isActive changes, React re-renders the component with the updated class names—this aligns with React's declarative approach, making your code more predictable and easier to maintain.
If you have specific styles for the active class (like transforming the lines into an X), just keep your existing CSS—this component will work seamlessly with it.
内容的提问来源于stack exchange,提问作者akorn3000

