使用未使用地圖功能/功能組件的早期答案來解決此問題。當我點擊我的卡片時,modal 只顯示最后一個 Modal 的資料:
export const ModalCard = (props) => {
const productData = props.data;
const [modal, setModal] = React.useState(false);
const toggle = () => setModal(!modal);
return (
<Row>
{productData.map((v, i) => (
<Col className="py-4 btn" key={i} xs={12} md={4} lg={2}>
<div className="pb-4" onClick={toggle}>
<div className="product_card_padding">
<div className="pt-4">
<span className="card_product_subtitle">{v.headline}</span>
</div>
</div>
<Modal isOpen={modal}
toggle={toggle}
centered
>
<ModalBody className="product_modal" onClick={toggle}>
<div className="row pt-3 bg_white">
<Col>
<div>
<span className="card_product_subtitle">{v.headline}</span>
</div>
</Col>
</div>
</ModalBody>
</Modal>
</div>
</Col>
))}
</Row>
);
}
uj5u.com熱心網友回復:
根據您的代碼,將打開多個模式,您將看到最后一個模式。
如果您有 10 個產品,則將打開 10 個模態。
我的建議是,您需要定義一個全域模態外部map函式,并且您需要定義一個新的狀態變數來表示要在模態上呈現的所選產品。
selectedInd保存要在模態上呈現的資料索引。
const [selectedInd, setSelectedInd] = React.useState(-1);
然后toggle函式將更改為設定 -1 以隱藏模式。
const toggle = () => setSelectedInd(-1);
并將模態移到外面map。
嘗試使用以下代碼模式。
export const ModalCard = (props) => {
const productData = props.data;
const [selectedInd, setSelectedInd] = React.useState(-1);
const toggle = () => setSelectedInd(-1);
const modal = selectedInd >= 0 && (productData && productData.length > selectedInd);
return (
<React.Fragment>
<Row>
{productData.map((v, i) => (
<Col className="py-4 btn" key={i} xs={12} md={4} lg={2}>
<div className="pb-4" onClick={()=>setSelectedInd(i)}>
<div className="product_card_padding">
<div className="pt-4">
<span className="card_product_subtitle">{v.headline}</span>
</div>
</div>
</div>
</Col>
))}
</Row>
{modal && <Modal isOpen={modal} toggle={toggle} centered>
<ModalBody className="product_modal" onClick={toggle}>
<div className="row pt-3 bg_white">
<Col>
<div>
<span className="card_product_subtitle">{productData[selectedInd].headline}</span>
</div>
</Col>
</div>
</ModalBody>
</Modal>}
</React.Fragment>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/463743.html
標籤:javascript 反应 引导模式
上一篇:在SpringAuthorizationServer(0.2.3 )中支持并發全堆疊MVC(session)認證以及無狀態JWT認證
