P粉6429205222023-08-18 13:11:55
You can create a more generic component for the modal that accepts props to customize the content of each car
Create a new component named CarModal
that accepts carImage
, carTitle
, and carDescription
as props.
Now you can use this component multiple times inside the Cars
component (the one where you want to show the cars) to create separate modals for each car, you just need to pass the appropriate props
// 导入 ... const style = { // ... }; function CarModal({ carImage, carTitle, carDescription }) { const [open, setOpen] = React.useState(false); const handleOpen = () => setOpen(true); const handleClose = () => setOpen(false); return ( <div> <Button onClick={handleOpen}>打开模态框</Button> <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <Typography id="modal-modal-title" variant="h6" component="h2"> {carTitle} </Typography> <Typography id="modal-modal-description" sx={{ mt: 2 }}> {carDescription} </Typography> <img src={carImage} alt={carTitle} /> </Box> </Modal> </div> ); }
export default function Cars() { // 导入 carModal // ... return ( <div> <CarModal carImage={Pagani} carTitle="Pagani汽车" carDescription="这是Pagani汽车的描述。" /> <CarModal carImage={Pagani1} carTitle="另一辆Pagani汽车" carDescription="这是另一辆Pagani汽车的描述。" /> // ... </div> ); }