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

React导航栏单选激活失效:子组件状态修改问题排查

问题修复:React导航栏单选激活状态失效

问题根源

你的代码核心问题出在HeaderList类组件中:

  • 你在组件内部维护了this.active实例属性,完全忽略了父组件传递的active props,导致父组件状态更新后,子组件的激活样式无法同步。
  • 多余地将children、onClickEvent存为实例属性,这会导致无法获取最新的props值,也是之前console.log失效的原因。

修复方案

方案1:改用函数组件(推荐,符合React现代实践)

将HeaderList改为无状态函数组件,直接使用props传递的值:

import React from "react";

interface HeaderListProps {
  children: string;
  onClickEvent?: () => void;
  active: boolean;
}

const HeaderList: React.FC<HeaderListProps> = ({ children, onClickEvent, active }) => {
  return (
    <li
      className={`p-1 rounded-xl cursor-pointer transition duration-200 hover:bg-red-300 hover:text-gray-900 hover:scale-105 hover:shadow-xl ${active ? "bg-red-300" : ""}`}
      onClick={onClickEvent}
    >
      {children}
    </li>
  );
};

export default HeaderList;

方案2:修复原类组件

如果坚持使用类组件,删除多余的实例属性,直接通过this.props访问值:

import React from "react";

interface HeaderListProps {
  children: string;
  onClickEvent?: () => void;
  active: boolean;
}

class HeaderList extends React.Component<HeaderListProps> {
  render() {
    return (
      <li
        className={
          "p-1 rounded-xl cursor-pointer transition duration-200 hover:bg-red-300 hover:text-gray-900 hover:scale-105 hover:shadow-xl" +
          (this.props.active ? " bg-red-300" : "")
        }
        onClick={this.props.onClickEvent}
      >
        {this.props.children}
      </li>
    );
  }
}

export default HeaderList;

效果验证

父组件Header的代码逻辑是正确的:

  • 通过useState集中管理激活项的索引active
  • 点击导航项时更新active为对应索引
  • 向每个HeaderList传递active={active === index}的判断值

修复子组件后,点击任意导航项,父组件状态更新会同步到子组件,实现仅单个项处于激活状态的需求,同时onClickEvent的回调也能正常触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 00:13:10