You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React自定义三线汉堡下拉组件:如何切换子元素active类

Pure React Implementation for Hamburger Menu Toggle

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:08:30