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

React模态框组件触发onClose时报错:onClose is not a function问题求助

解决Modal组件onClose不是函数的报错问题

嘿,这问题我太熟了!你踩了React组件定义的一个常见小坑——组件的参数是props对象,不是单个属性。

问题根源

你的Modal组件是这么定义的:

const Modal = (onClose) => { ... }

这里的onClose其实是React传给组件的整个props对象,而不是你父组件传入的那个onClose函数。所以当你点击按钮调用onClose()时,本质是在调用一个对象,自然会报错“onClose is not a function”。

解决方案

把组件参数改成解构props,直接取出onClose函数就行,两种写法都可以:

写法1:直接解构参数

const Modal = ({ onClose }) => {
  return (
    <div className="Background" >
      <div className="Container">
        <div className="Title">Title of the modal</div>
        <div className="Body">Body of the modal</div>
        <div className="Footer">
          <button type="button" onClick={() => onClose()}>Cancel</button>
        </div>
      </div>
    </div>
  );
};

写法2:先接收props再解构

如果你需要用到多个props,这种写法更清晰:

const Modal = (props) => {
  const { onClose } = props;
  return (
    <div className="Background" >
      <div className="Container">
        <div className="Title">Title of the modal</div>
        <div className="Body">Body of the modal</div>
        <div className="Footer">
          <button type="button" onClick={() => onClose()}>Cancel</button>
        </div>
      </div>
    </div>
  );
};

验证父组件调用

你父组件传入onClose的写法是完全正确的:

<Modal onClose={() => this.setState((prevState) => ({ 
  showModal: { ...prevState.showModal, confirmation: false, }, 
}))} />

只要子组件正确解构props,点击取消按钮就能正常触发关闭逻辑了。

内容的提问来源于stack exchange,提问作者coding1223322

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 11:12:46