cyr*_*ilb 1 modal-dialog bootstrap-modal reactjs
我是编码初学者。我正在创建我的平面设计师作品集。我已将所有投资组合内容(缩略图、客户名称、描述...)放入 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;
Run Code Online (Sandbox Code Playgroud)
我希望模态显示相应的项目详细信息。感谢您的帮助。
您只需要 1 个模态并在item单击时动态传递数据,
<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>
Run Code Online (Sandbox Code Playgroud)
现在在你的handleShow函数中你可以设置item状态,
this.handleShow = (item) => {
this.setState({activeItem:item}, ()=> this.setState({ show: true }));
};
Run Code Online (Sandbox Code Playgroud)
使用callback显示模式,这确保activeItem了最新的点击item。
初始状态,
this.state = {
error: null,
isLoaded: false,
items: [],
projectName: "",
show: false,
activeItem:'' //new added
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1301 次 |
| 最近记录: |