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

React实现列表项点击切换显示对应段落内容问题求助

解决点击列表项互斥显示对应内容的问题

问题核心在于每个SingleQuestion组件独立维护自身的显示状态,导致点击多个列表项后所有内容都会保留。要实现点击一项显示对应内容、其他内容自动隐藏的互斥效果,需要把状态**提升到父组件Questions**统一管理。

修改步骤:

  1. 父组件Questions:添加状态管理当前选中的问题ID,并定义切换选中项的函数,传递给子组件。
  2. 子组件SingleQuestion:移除自身状态,根据父组件传递的选中ID判断是否显示内容,点击时通知父组件切换选中项。

修改后的代码:

Questions.jsx

import { useState } from "react";
import SingleQuestion from "./SingleQuestion";
import classes from "./Question.module.css";

const questions = [
  {
    id: 1,
    title: "Step 1",
    info: "paragraph 1 text",
  },
  {
    id: 2,
    title: "Step 2",
    info: "paragraph 2 text",
  },
  {
    id: 3,
    title: "Step 3",
    info: "paragraph 3 text",
  },
  {
    id: 4,
    title: "Step 4",
    info: "paragraph 4 text",
  },
];

const Questions = () => {
  // 管理当前选中的问题ID,初始为null表示无选中项
  const [selectedId, setSelectedId] = useState(null);

  // 切换选中项的函数
  const handleSelectQuestion = (id) => {
    // 点击当前选中项可取消选中(可选逻辑)
    setSelectedId(prevId => prevId === id ? null : id);
  };

  return (
    <main>
      <h1 className="infoTitle">We have answers</h1>
      <div className={classes.container}>
        {questions.map((question) => {
          return (
            <SingleQuestion
              key={question.id}
              {...question}
              selectedId={selectedId}
              onSelect={handleSelectQuestion}
            />
          );
        })}
      </div>
    </main>
  );
};
export default Questions;

SingleQuestion.jsx

import React from "react";
import classes from "./Question.module.css";

const SingleQuestion = ({ title, info, id, selectedId, onSelect }) => {
  // 判断当前问题是否被选中
  const isSelected = selectedId === id;

  return (
    <section className={classes.elementBin}>
      <ul>
        <li
          className={`${classes.hi} ${isSelected ? classes.active : ''}`} // 可选:添加选中样式
          onClick={() => onSelect(id)}
        >
          {title}
        </li>
      </ul>
      {/* 只有选中时才显示内容 */}
      {isSelected && <p>{info}</p>}
    </section>
  );
};

export default SingleQuestion;

额外说明:

  • 若不需要点击选中项取消显示的功能,可将handleSelectQuestion中的逻辑简化为setSelectedId(id)。
  • 可以给classes.active添加自定义样式,比如改变文字颜色、添加下划线,让选中状态更直观。

内容的提问来源于stack exchange,提问作者maxheezy's

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:00:19