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

如何在MUI CardMedia中处理视频加载错误?

符合React/MUI风格的视频加载错误处理方案

当然有,结合React的状态管理和MUI的组件体系,就能实现既符合风格又友好的错误处理逻辑,具体实现如下:

完整实现代码

import { useState } from 'react';
import { CardMedia, Typography, Box } from '@mui/material';

const VideoCard = ({ videoUrlBase, currentLoop, handleFullScreen, handleOnTimeUpdate, videoRef }) => {
  // 状态存储视频错误信息
  const [videoError, setVideoError] = useState(null);
  // 假设setIsPlaying是父组件传入或内部定义的状态方法
  const [isPlaying, setIsPlaying] = useState(true);

  // 视频错误处理函数
  const handleVideoError = (e) => {
    const error = e.target.error;
    let errorMsg = '视频加载失败,请稍后重试';
    
    // 根据错误码细化提示信息
    switch(error.code) {
      case error.MEDIA_ERR_ABORTED:
        errorMsg = '视频加载被中断';
        break;
      case error.MEDIA_ERR_NETWORK:
        errorMsg = '网络异常,视频加载失败';
        break;
      case error.MEDIA_ERR_DECODE:
        errorMsg = '视频格式不支持或文件损坏';
        break;
      case error.MEDIA_ERR_SRC_NOT_SUPPORTED:
        errorMsg = '视频地址无效或不被支持';
        break;
    }
    setVideoError(errorMsg);
    setIsPlaying(false);
  };

  // 如果加载出错,展示MUI风格的错误界面
  if (videoError) {
    return (
      <Box 
        sx={{
          width: '100%',
          aspectRatio: '16/9',
          bgcolor: 'grey.100',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          p: 2,
          textAlign: 'center'
        }}
      >
        <Typography color="error" variant="h6" gutterBottom>
          视频加载失败
        </Typography>
        <Typography variant="body1">
          {videoError}
        </Typography>
      </Box>
    );
  }

  // 正常状态下渲染视频组件
  return (
    <CardMedia
      component="video"
      ref={videoRef}
      src={`${videoUrlBase}/loop/stream/${currentLoop.id}`}
      onClick={handleFullScreen}
      onTimeUpdate={handleOnTimeUpdate}
      onEnded={() => setIsPlaying(false)}
      onError={handleVideoError} {/* 绑定React合成事件处理错误 */}
      autoPlay
      loop
    />
  );
};

export default VideoCard;

核心要点

  • React合成事件绑定:直接给CardMedia绑定onError事件,这是React官方推荐的事件处理方式,完全符合React组件化逻辑,无需手动操作原生DOM。
  • 状态驱动UI切换:用videoError状态控制错误界面和视频组件的切换,契合React"数据驱动视图"的核心思想。
  • MUI风格统一:使用MUI的Box、Typography组件构建错误提示界面,保证和你的应用UI风格一致,避免突兀感。
  • 精准错误提示:通过HTML5 Video的错误码细分提示内容,让用户清楚知道失败原因,提升体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:13:25