reactjs - 在映射 ReactJS 中显示/隐藏 div
问题描述
我目前正在学习 ReactJS,并且在尝试隐藏/显示 div 时遇到问题!以下代码正在运行,但是当我单击“了解更多”按钮时,它会隐藏每张卡片上的每个描述,但我想仅在单击它的位置显示/隐藏描述。
import Axios from 'axios';
import React, { useEffect, useState } from 'react';
import JobApplicationList from './JobApplicationList';
import Card from "react-bootstrap/Card";
import ScriptTag from 'react-script-tag';
export default class Home extends React.Component{
constructor(){
super()
this.state={
showMe:true,
advLists: []
}
}
operation(){
this.setState({
showMe:!this.state.showMe
})
}
componentDidMount() {
Axios.get(`http://localhost:3001/get/adv`)
.then(res => {
const advLists = res.data;
this.setState({ advLists });
})
}
render(){
return (
<div className="main-page">
<div className="adv_container">
{this.state.advLists.map((val, key) => {
return (
<div className="card_">
<Card style={{ width: "100%" }}>
<Card.Body>
<Card.Title>{val.compName}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">
{val.city} | {val.compWebsite}
</Card.Subtitle>
<Card.Subtitle className="mb-2 text-muted">
{val.salaire} €
</Card.Subtitle>
{ this.state.showMe?
<div className="description">
<Card.Text>{val.description}</Card.Text>
</div>
:null
}
<Card.Link onClick={()=> this.operation()} id="toto" href="#">Learn more</Card.Link>
<Card.Link href="#">Apply</Card.Link>
</Card.Body>
</Card>
</div>
);
})}
</div>
</div>
)
}
}
我有点知道出了什么问题,当我按下按钮时,我会为每张卡提供 showMe 状态,但我不知道如何解决它!在此先感谢您的帮助。
解决方案
使初始showMe
状态为 null 并转换operation
为采用索引进行切换。如果索引已保存在状态中,则设置回 null。
operation(index) {
this.setState({
showMe: this.state.showMe === index ? null : index,
})
}
使用映射索引传递给处理程序并根据showMe
状态检查此索引以显示卡片。
{this.state.advLists.map((val, key) => {
return (
<div className="card_">
<Card style={{ width: "100%" }}>
<Card.Body>
<Card.Title>{val.compName}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">
{val.city} | {val.compWebsite}
</Card.Subtitle>
<Card.Subtitle className="mb-2 text-muted">
{val.salaire} €
</Card.Subtitle>
{this.state.showMe === key && ( // <-- check if index/key matches
<div className="description">
<Card.Text>{val.description}</Card.Text>
</div>
)}
<Card.Link
onClick={() => this.operation(key)} // <-- pass key/index to toggle
id="toto" href="#"
>
Learn more
</Card.Link>
<Card.Link href="#">Apply</Card.Link>
</Card.Body>
</Card>
</div>
);
})}
推荐阅读
- amazon-web-services - 如何在 AWS 中定义仅允许使用预定义模板创建堆栈的策略/角色/权限
- javascript - 我将如何根据左侧两列中的任何一列中是否存在值来向 Google 表格添加一个复选框?
- node.js - TypeORM 堆栈跟踪未在我的代码中显示错误来源
- r - 如何在 R chordDiagram 中为标签着色
- python - PyQt5:用户可以在其中绘制的绘图表面
- flutter - 如何根据字符串的相同值显示来自第二个 JSON 的数据
- javascript - 如何使用 Apple Mapkit 在 Web 查看器中使用 javascript 访问 filemaker 脚本?
- javascript - React Router 在同一页面上渲染目标页面
- prolog - 如何在 Prolog 中配对列表中的所有元素?
- linux - 防止 mkdir -p 覆盖目录和 cp 覆盖文件