reactjs - React-Bootstrap modal 只取地图的最后一项
问题描述
我是编码的初学者。我正在创建我的平面设计师作品集。我已将所有投资组合内容(缩略图、客户名称、描述...)放入 JSON 文件中名为“投资组合”的数组中。数组中的每个项目都是一个不同的项目。我显示了一系列缩略图,当我单击缩略图时,会打开一个包含项目详细信息的模式。
我映射到我的“投资组合”数组以显示画廊,这很有效。但是当我打开模式时,它总是显示我数组的最后一项。
import React from 'react';
import Modal from 'react-bootstrap/Modal';
class Portfolio extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
error: null,
isLoaded: false,
items: [],
projectName: "",
show: false
};
this.handleShow = () => {
this.setState({ show: true });
};
this.handleClose = () => {
this.setState({ show: false });
};
}
componentDidMount() {
fetch("https://api.myjson.com/bins/1cbaj5")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.portfolio
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const {error, isLoaded, items} = this.state;
if (error) {
return <div>Erreur : {error.message}</div>;
} else if (!isLoaded) {
return <div>Chargement…</div>;
} else {
return (
<div id="portfolio">
<h2>Portfolio</h2>
<ul className="portfolio-list">
{items.map(item => (
<li key={item.client}>
<div className="vignette">
<button onClick={() => this.handleShow()}>
<h4>{item.client}</h4>
<div className="filtre"></div>
<img src={item.vignette} alt={item.titre} />
</button>
<Modal show={this.state.show} onHide={this.handleClose}>
<Modal.Header closeButton>
<h3>{item.client}</h3>
</Modal.Header>
<Modal.Body>
<p>{item.description}</p>
</Modal.Body>
</Modal>
</div>
</li>
))}
</ul>
</div>
);
}
}
}
export default Portfolio;
我希望模态显示相应的项目详细信息。谢谢您的帮助。
解决方案
item
您只需要 1 个模态并在点击时动态传递数据,
<ul className="portfolio-list">
{items.map(item => (
<li key={item.client}>
<div className="vignette">
<button onClick={()=> this.handleShow(item)}> //Pass complete item object here
<h4>{item.client}</h4>
<div className="filtre"></div>
<img src={item.vignette} alt={item.titre} />
</button>
</div>
</li>
))}
<Modal show={this.state.show} onHide={this.handleClose}> //Only one modal
<Modal.Header closeButton>
<h3>{this.state.activeItem.client}</h3>
</Modal.Header>
<Modal.Body>
<p>{this.state.activeItem.description}</p>
</Modal.Body>
</Modal>
</ul>
现在在你的handleShow
函数中你可以设置item
状态,
this.handleShow = (item) => {
this.setState({activeItem:item}, ()=> this.setState({ show: true }));
};
用于callback
显示模态,确保activeItem
最近点击item
。
初始状态,
this.state = {
error: null,
isLoaded: false,
items: [],
projectName: "",
show: false,
activeItem:'' //new added
};
推荐阅读
- puppeteer - Puppeteer 使用 addScriptTag 添加 jQuery:“此文档需要 'TrustedScript' 分配”
- c++ - 在Qt中按下按钮时在小部件内显示带有动画的小部件
- python - Live Plotting in PyQt5 GUI
- java - JTable disappears when implementing TableModelListener
- mongoose - Remove Result Type for Mongoose Nestjs Promises
- c - 我如何编写 C 编程大写字母分隔函数?
- python-3.x - 需要帮助将 Unix 时间戳解码为日期(不和谐)
- arrays - 有限的字符串在 C 中接受无限的字符
- amazon-web-services - 如何从消息 ID 调试 AWS SNS 的传递状态?
- similarity - 微调对象关键点相似度(OKS)