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

为什么Material-UI v4自定义Snackbar过渡会出现children类型不兼容报错

问题原因

Material-UI v4的Slide过渡组件限定children属性只能是ReactElement类型或undefined,但SnackbarProvider传递给过渡组件的props中children类型为更宽泛的ReactNode(包含null、字符串、数字等非React元素类型),二者类型不匹配触发ts报错。

解决方案

下面是3种可行的修复方式:

  • 方案1:添加类型断言快速修复
    直接对children做类型断言,明确告知TypeScript传入的children符合Slide组件的类型要求,代码如下:
    import React, { forwardRef } from 'react';
    import { Slide, SlideProps } from '@material-ui/core';
    import { SnackbarProvider } from 'notistack';
    
    <SnackbarProvider
      maxSnack={3}
      TransitionComponent={forwardRef<HTMLDivElement, SlideProps>(function Transition(
        props,
        ref
      ) {
        return <Slide direction="up" ref={ref} {...props} children={props.children as React.ReactElement} />
      })}
    >
    
  • 方案2:添加类型守卫保证类型安全
    先校验children是否为合法React元素再传递,避免类型断言带来的运行时风险,代码如下:
    TransitionComponent={forwardRef(function Transition(
      props,
      ref
    ) {
      const { children, ...restProps } = props;
      if (!React.isValidElement(children)) return null;
      return <Slide direction="up" ref={ref} {...restProps}>{children}</Slide>
    })}
    
  • 方案3:对整个过渡组件做类型断言
    适合临时快速修复,无需修改组件内部逻辑,代码如下:
    TransitionComponent={React.forwardRef(function Transition(
      props,
      ref
    ) {
      return <Slide direction="up" ref={ref} {...props} />
    }) as React.ElementType}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:54:05