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

React中如何实现多下拉框独立动画且避免代码重复?

解决多个下拉框同时展开的问题

你当前的问题核心是所有下拉框共用了同一个布尔状态drop,点击任何一个触发状态切换时,所有依赖这个状态的下拉都会同步展开/收起。下面提供两种不用写多个函数的解决思路:

方案一:封装独立的下拉子组件

把单个下拉项封装成独立组件,让每个组件自己管理展开状态,互不干扰,复用性拉满:

import { useState } from 'react';
import { AiOutlineMinus } from 'react-icons/ai';
import { BsPlus } from 'react-icons/bs';

// 单个下拉项组件,可复用
const DropdownItem = ({ title, content }) => {
  const [isOpen, setIsOpen] = useState(false);

  const toggleDropdown = () => {
    setIsOpen(!isOpen);
  };

  return (
    <div className="dropdown-item">
      <div onClick={toggleDropdown} style={{ cursor: 'pointer' }}>
        <h1>{title}</h1>
        {isOpen ? <AiOutlineMinus /> : <BsPlus />}
      </div>
      <div className={isOpen ? "h-auto flex-col" : "fixed left-[100%]"}>
        {content}
      </div>
    </div>
  );
};

// 主组件调用
const Dropdown = () => {
  return (
    <div>
      <DropdownItem title="Help" content={<h1>hello</h1>} />
      <DropdownItem title="Um" content={<h1>hello</h1>} />
      {/* 后续加更多下拉直接加组件即可 */}
    </div>
  );
};

export default Dropdown;

方案二:用对象状态管理每个下拉的展开状态

在父组件用对象记录每个下拉的状态,通过传递标识来单独切换对应下拉的状态,不用新增组件:

import { useState } from 'react';
import { AiOutlineMinus } from 'react-icons/ai';
import { BsPlus } from 'react-icons/bs';

const Dropdown = () => {
  // 用对象存储每个下拉的展开状态,key为下拉唯一标识
  const [openStates, setOpenStates] = useState({
    help: false,
    um: false
  });

  // 通用切换函数,接收下拉标识作为参数
  const toggleDropdown = (dropdownKey) => {
    setOpenStates(prevState => ({
      ...prevState,
      [dropdownKey]: !prevState[dropdownKey]
    }));
  };

  return (
    <div>
      <div onClick={() => toggleDropdown('help')} style={{ cursor: 'pointer' }}>
        <h1>Help</h1>
        {openStates.help ? <AiOutlineMinus /> : <BsPlus />}
      </div>
      <div className={openStates.help ? "h-auto flex-col" : "fixed left-[100%]"}>
        <div><h1>hello</h1></div>
      </div>

      <div onClick={() => toggleDropdown('um')} style={{ cursor: 'pointer' }}>
        <h1>Um</h1>
        {openStates.um ? <AiOutlineMinus /> : <BsPlus />}
      </div>
      <div className={openStates.um ? "h-auto flex-col" : "fixed left-[100%]"}>
        <div><h1>hello</h1></div>
      </div>
    </div>
  );
};

export default Dropdown;

两种方案都不需要为每个下拉写单独的函数,方案一更适合需要频繁新增下拉的场景,方案二适合下拉数量较少、不想新增组件的情况。

内容的提问来源于stack exchange,提问作者queercoded

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:20:27