点击循环中的更改图标



我在映射数组时包含了一个图标,我需要更改特定迭代上的图标。单击后,我还想在单击图标时呈现测试结果。

我不确定如何获得一个特定于此迭代的唯一值,以处理此更改,还是我的结构完全错误?

**进入睡眠找到解决方案=封装**

映射组件,使布尔变量在该迭代的局部范围内。

以下的共享解决方案

const Students = ({students}) => {
const [showTests, setShowTests] = useState(false);
return (
<div className="wrapper" key={student.id}>
<div className="img-container">
<img src={student.pic} alt="student" />
</div>
<div className="content">
<h1>
{student.firstName.toUpperCase()} {student.lastName.toUpperCase()}
</h1>
<p>Email: {student.email}</p>
<p>Company: {student.company}</p>
<p>Skill: {student.skill}</p>
<p>Average: {averageGrade(student.grades)}%</p>
{showTests && <TestResults results={student.tests} />}
</div>
{showTests ? (
<FontAwesomeIcon
onClick={() => setShowTests(!showTests)}
className="faIcon"
icon={faMinus}
/>
) : (
<FontAwesomeIcon
onClick={() => setShowTests(!showTests)}
className="faIcon"
icon={faPlus}
/>
)}
</div>
);
}
const Main = () => {
return (
<div className="main" id="main">
{filteredStudents.map(student => (
//each iteration is a unique component
<Students student={student} />
))}
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

提前感谢的任何建议

返回必须始终具有顶级标记。

const Students = ({ students }) => {
return (
<>
{students.map((student, i) => (
<div className="wrapper" key={student.id}>
<div className="img-container">
<img src={student.pic} alt="student" />
</div>
<div className="content">
<h1>
{student.firstName.toUpperCase()}{" "}
{student.lastName.toUpperCase()}
</h1>
<p>Email: {student.email}</p>
<p>Company: {student.company}</p>
<p>Skill: {student.skill}</p>
<p>Average: {averageGrade(student.grades)}%</p>
{faMinus && <TestResults results={student.tests} />}
</div>
<FontAwesomeIcon
id={i}
onClick={(e) => handleTests(e.target.id)}
className="faIcon"
icon={current ? faPlus : faMinus}
/>
</div>
))}
</>
);
};

如果这是您的想法,请告诉我。只需将索引存储在状态变量中并与之进行比较。当他们单击时,将索引更改为他们单击的索引。

const Students = ({students}) => {
const [selectedIndex, setSelectedIndex] = useState(0)

function handleTests(id, index) {   //NEW
//Your current code
setSelectedIndex(index)   //NEW
}
return (
{students.map((student, i) => (
<div className="wrapper" key={student.id}>
<div className="img-container">
<img src={student.pic} alt="student" />
</div>
<div className="content">
<h1>
{student.firstName.toUpperCase()} {student.lastName.toUpperCase()}
</h1>
<p>Email: {student.email}</p>
<p>Company: {student.company}</p>
<p>Skill: {student.skill}</p>
<p>Average: {averageGrade(student.grades)}%</p>
{selectedIndex == i && <TestResults results={student.tests} />}   //NEW
</div>
<FontAwesomeIcon
id={i}
onClick={e => handleTests(e.target.id, i)}   //NEW
className="faIcon"
icon={selectedIndex == i ? faPlus : faMinus}
/>
</div>
))}
)
}

最新更新