首页 > 解决方案 > Material-ui - 单击按钮时,模态打开多次

问题描述

我有这个渲染():

render() {
const classes = this.useStyles();

return (
    <Paper style={classes.root}>
        <Table style={classes.table}>
            <TableBody>
                {this.state.deadTopics.map(row => (
                    <TableRow key={row.id}>
                        <TableCell component="th" scope="row">
                            {row.id}
                        </TableCell>
                        <TableCell align="right">
                            <div>
                                <Button variant="outlined" color="primary" onClick={this.handleOpen}>
                                    Open alert dialog
                                </Button>
                                <Modal
                                    aria-labelledby="simple-modal-title"
                                    aria-describedby="simple-modal-description"
                                    open={this.state.setOpen}
                                    onClose={this.handleClose}
                                >
                                    <div style={classes.modal} style={classes.paper}>
                                        <p>ola</p>
                                    </div>
                                </Modal>
                            </div>
                        </TableCell>
                    </TableRow>
                ))}
            </TableBody>
        </Table>
    </Paper>
);
}

看起来不错,按预期渲染。 我的问题是: 元素 deadTopics 是一个数组,它生成表格的行,当我单击按钮打开模态时,它会打开多个模态,而不是行中唯一一个特定的模态。

我怎样才能防止这种情况发生?我希望当我单击按钮打开模态时,它只显示特定的模态。

标签: javascriptreactjsmaterial-ui

解决方案


这是因为您正在打开具有相同状态“setOpen”的所有模态。您需要为每一行设置不同的州名。每一行都有一个唯一的州名称,如下所示 -

open={this.state['some-unique-name']}

example - `setOpen-${row.id}`

在 onClick 功能中 -

onClick={() => this.handleOpen(row.id)}

handleOpen = (rowId) => {
     this.setState({
       [`setOpen-${rowId}`]: true
     })

推荐阅读