React MUI Modal组件初始化打开且无法关闭问题咨询
问题根因
- state字段定义冗余且使用错误:你定义了
open和setOpen两个布尔状态,但修改逻辑只操作setOpen,Modal的显隐属性却绑定了从未修改的open字段,还错误将布尔值作为函数调用 - Modal的
open参数要求传入布尔值,你传入了箭头函数,函数本身属于真值,因此组件挂载后Modal直接默认打开,且永远不会响应关闭操作
修复后完整代码
import React, { Component } from 'react'; import Box from '@mui/material/Box'; import Button from '@mui/material/Button'; import Typography from '@mui/material/Typography'; import Modal from '@mui/material/Modal'; const style = { position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: 400, bgcolor: 'background.paper', border: '2px solid #000', boxShadow: 24, p: 4 }; export class Contact extends Component { constructor(props) { super(props); this.state = { open: false } this.handleOpen = this.handleOpen.bind(this); this.handleClose = this.handleClose.bind(this); } static displayName = Contact.name; handleOpen() { this.setState({ open: true }); } handleClose() { this.setState({ open: false }); } render() { return( <div> <div className="center"> <Button onClick={this.handleOpen}>Contact us</Button> </div> <Modal open={this.state.open} onClose={this.handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <Typography id="modal-modal-title" variant="h6" component="h2"> Contact us </Typography> <Typography id="modal-modal-description" sx={{ mt: 2 }}> Contact us at hello @ mycompany.com </Typography> </Box> </Modal> </div> ); } }
修复说明
- 仅保留
open状态控制Modal显隐,删除冗余的setOpen字段 - Modal的
open属性直接传入this.state.open布尔值,初始化值为false,默认关闭 - 简化事件绑定写法,无需额外套一层箭头函数调用已经bind过的方法
- MUI Modal原生支持点击蒙层、按ESC触发
onClose事件,无需额外逻辑即可实现点击弹窗以外区域关闭的需求
内容的提问来源于stack exchange,提问作者Soleil
相关产品推荐
相关产品推荐

