我正在尝试从一组卡中打开一个模式对话框,这些卡一直从组件接收的数据中循环出来。我无法弄清楚如何使模式从被点击的卡中获取适当的数据。在下面的代码中,我试图将模态置于循环之外,但后来我无法弄清楚如何将被点击的卡片的ID传递给将控制模态的新函数
这里是管理纸牌循环并包含模式的组件
import React, {Component} from 'react';
import {Nav, NavItem, NavLink, Card, CardImg, CardText,
CardBody, CardTitle, CardSubtitle, FormGroup, Input, Col, Button, Modal, ModalHeader, ModalBody} from 'reactstrap';
import classnames from 'classnames';
class ProductCard extends Component {
constructor(props){
super(props);
this.state={
productList: this.props.products,
isModalOpen: false
}
this.toggleModal = this.toggleModal.bind(this)
}
toggleModal() {
this.setState({
isModalOpen: !this.state.isModalOpen
});
}
render(){
return(
this.state.productList.map(prod => (
<div key={prod.prod_id} className="col-12 col-md-3 mb-4 rowCard" onClick={this.toggleModal}>
<Card>
<CardImg top width="100%" src={prod.prod_image} alt={prod.prod_name_eng}/>
<CardBody>
<CardTitle>{prod.prod_name_eng}</CardTitle>
<CardSubtitle>{prod.prod_cost_total}</CardSubtitle>
<CardText>{prod.prod_description}</CardText>
</CardBody>
</Card>
<Modal isOpen={this.state.isModalOpen} toggle={this.toggleModal}>
<ModalHeader toggle={this.toggleModal}>{prod.prod_name_eng}</ModalHeader>
<ModalBody>{prod.prod_description}</ModalBody>
</Modal>
</div>
))
);
}
}
欢迎任何帮助!感谢
我建议将莫代尔(Modal)移出地图,因为这会使事情变得比原先要复杂。如果执行此操作,则toggleModal
方法将负责接受索引(由map
函数提供),然后只需要检索模式元素的正确文本即可。
toggleModal(index) {
this.setState({
cardIndex: index,
isModalOpen: !this.state.isModalOpen
});
}
然后您是模态的,只需引用状态的productList,访问索引并获得标题和描述:
class ProductCard extends Component {
constructor(props) {
super(props);
this.state = {
productList: this.props.products,
cardIndex: null,
isModalOpen: false
};
this.toggleModal = this.toggleModal.bind(this);
}
toggleModal(id) {
console.log(id);
this.setState({
cardIndex: id,
isModalOpen: !this.state.isModalOpen
});
}
render() {
const { productList, cardIndex } = this.state;
console.log("CardIndex: ", cardIndex);
console.log("Product: ", productList[cardIndex]);
return (
<Fragment>
{productList.map((prod, index) => {
return (
<div
key={prod.prod_id}
className="col-12 col-md-3 mb-4 rowCard"
onClick={e => this.toggleModal(index)}
>
<Card>
<CardImg top src={prod.prod_image} alt={prod.prod_name_eng} />
<CardBody>
<CardTitle>{prod.prod_name_eng}</CardTitle>
<CardSubtitle>{prod.prod_cost_total}</CardSubtitle>
<CardText>{prod.prod_description}</CardText>
</CardBody>
</Card>
</div>
);
})}
<Modal
isOpen={this.state.isModalOpen}
toggle={e => this.toggleModal(cardIndex)}
>
<ModalHeader toggle={e => this.toggleModal(cardIndex)}>
{cardIndex !== null && productList[cardIndex].prod_name_eng}
</ModalHeader>
<ModalBody>
{cardIndex !== null && productList[cardIndex].prod_description}
</ModalBody>
</Modal>
</Fragment>
);
}
}
这是工作版本的codesandbox link: