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

React点击侧边栏标题后模态框无法显示选中项内容问题

问题解决:模态框无法显示选中项内容

你的问题出在状态管理没有存储选中的具体项数据,直接给你修正方案:

核心问题分析

  • selectedItem初始设为false,点击时只把它改成true,根本没存你点击的那个item对象,所以模态框里selectedItem.title自然拿不到值
  • 模态框渲染的else分支返回!selectedItem完全没必要,直接不渲染就行

修改后的完整代码

import React, { useState } from "react";
import "../sidebarStyles.css";

function Modal({ title, text, closeModal }) {
  return (
    <div className="modal">
      <div className="modal-content">
        <span className="close" onClick={closeModal}>
          X
        </span>
        <div className="content">
          <h2>{title}</h2>
          <p>{text}</p>
        </div>
      </div>
    </div>
  );
}

const sidebarTitle = [
  {
    title: "Text",
    text: "Modal",
  },
  {
    title: "Scope",
    text: "Modal",
  },
  {
    title: "Analysis",
    text: "Modal",
  },
];

function Sidebar() {
  // 初始设为null,表示未选中任何项
  const [selectedItem, setSelectedItem] = useState(null);

  // 点击时传入当前item,把状态设为选中的对象
  const handleTitleClick = (item) => {
    setSelectedItem(item);
  };

  // 关闭时把状态重置为null
  const closeModal = () => {
    setSelectedItem(null);
  };

  return (
    <div className="sidebar">
      {sidebarTitle.map((item, index) => (
        <div key={index}>
          {/* 点击时把当前item传给处理函数 */}
          <p onClick={() => handleTitleClick(item)}>{item.title}</p>
        </div>
      ))}
      {/* 判断selectedItem是否存在,存在就渲染模态框 */}
      {selectedItem && (
        <Modal
          title={selectedItem.title}
          text={selectedItem.text}
          closeModal={closeModal}
          className="modal"
        />
      )}
    </div>
  );
}

export default Sidebar;

关键改动点

  1. 状态初始化:把selectedItem初始值从false改成null,用来区分「未选中」和「选中某一项」的状态
  2. 点击事件处理:handleTitleClick接收当前点击的item参数,调用setSelectedItem把状态更新为这个item对象
  3. 模态框渲染逻辑:用selectedItem && ...替代原来的三元表达式,只要选中了项就渲染模态框,不需要多余的else分支
  4. 关闭模态框:把状态重置回null,恢复未选中状态

这样点击侧边栏的每个标题时,对应的title和text就能正常显示在模态框里了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:01:13