Вы создаете три разных модала в вашей функции stationData.map()
, и каждый из них зависит от одного состояния this.state.open
.Поэтому, когда нажата кнопка, все три открываются, и вы видите последнюю сверху.Таким образом, всегда видно 3.
Что вам нужно сделать, это создать только один модал и отслеживать, какая кнопка нажата в новом состоянии this.state.stationNumber
.Таким образом, будет запущен единственный модал, и он будет знать, что визуализировать из состояния.
Вот ваш модифицированный код, я добавил комментарии, где это необходимо:
class Dashboard extends React.Component {
state = {
open: false,
stationNumber: null,
stationData: [
{ id: 1, number: "1" },
{ id: 2, number: "2" },
{ id: 3, number: "3" }
]
};
handleOpen = stationNumber => () => {
// get which button was pressed via `stationNumber`
// open the modal and set the `stationNumber` state to that argument
this.setState({ open: true, stationNumber: stationNumber });
};
handleClose = () => {
this.setState({ open: false });
};
render() {
const { stationData } = this.state;
return (
<div style={styles.wrapper}>
<div style={styles.body}>
<Paper square elevation={0} style={styles.container}>
{stationData.map((station, index) => (
<div key={index}>
<Button
variant="contained"
color="primary"
style={styles.button}
// pass which button was clicked as an argument
onClick={this.handleOpen(station.number)}
>
{station.number}
</Button>
</div>
))}
</Paper>
{/* add only one modal */}
<Modal open={this.state.open} onClose={this.handleClose}>
{/* display the content based on newly set state */}
<div style={styles.modal}>{this.state.stationNumber}</div>
</Modal>
</div>
</div>
);
}
}
![Edit Material UI Playground](https://codesandbox.io/static/img/play-codesandbox.svg)