You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:24:03