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

Material UI v5升级:Modal组件TransitionProps的onEntering不触发求助

Material UI v5 Modal TransitionProps onEntering 触发问题解决

问题拆解

  1. 无报错但不触发:你写的匿名函数虽然语法合法,但onEntering要求接收HTMLElement和isAppearing两个参数,签名不匹配可能导致过渡组件忽略该回调;另外如果doSomething依赖组件状态,闭包也可能让逻辑未按预期执行。
  2. 无限循环+类型错误:onEntering: doSomething()是直接执行函数,把返回值(void)传给了属性,而非传递函数引用。这会导致组件每次渲染都执行doSomething,触发无限循环,同时类型完全不匹配,因此报错。

正确实现方式

方法1:补全函数签名

直接编写符合要求的回调,即便用不到参数也要保留形参:

<Modal
  TransitionProps={{
    onEntering: (node, isAppearing) => {
      doSomething();
    }
  }}
>
  {/* Modal内容 */}
</Modal>

TypeScript环境可添加类型标注:(node: HTMLElement, isAppearing: boolean): void => {...}

方法2:传递函数引用

如果doSomething不需要过渡回调的参数,调整函数定义兼容签名:

// 定义兼容的函数
const doSomething = (node, isAppearing) => {
  // 你的业务逻辑
};

// 使用时直接传递函数引用
<Modal
  TransitionProps={{ onEntering: doSomething }}
>
  {/* Modal内容 */}
</Modal>

方法3:用useCallback缓存(依赖状态时)

如果doSomething用到了组件的state/props,用useCallback缓存函数,避免过渡组件不必要的重渲染:

import { useCallback } from 'react';

// ...

const handleEntering = useCallback((node, isAppearing) => {
  doSomething(); // 这里可安全访问组件状态
}, [/* 填写doSomething依赖的状态/道具 */]);

<Modal
  TransitionProps={{ onEntering: handleEntering }}
>
  {/* Modal内容 */}
</Modal>

补充说明

Material UI v5的Modal默认使用Fade作为过渡组件,TransitionProps会直接传递给该过渡组件。如果自定义了过渡组件(比如Slide),需对应查看该组件的回调参数要求,确保签名匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:25:18