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

如何在TypeScript中正确声明react-h5-audio-player的useRef类型

正确声明react-h5-audio-player的useRef类型(避免any)

不用自行定义复杂接口,直接复用库导出的官方类型就能解决问题,具体步骤如下:

  1. 导入库与对应类型
    从react-h5-audio-player中导入组件本身:
import H5AudioPlayer from 'react-h5-audio-player';
  1. 正确声明useRef泛型
    组件的ref指向的是H5AudioPlayer的实例,因此直接将泛型参数设为H5AudioPlayer即可——useRef本身返回的就是MutableRefObject类型,不需要嵌套声明:
const playerRef = useRef<H5AudioPlayer>(null);
  1. 简化时间更新逻辑
    利用可选链操作符简化空值判断,同时注意playerRef是稳定引用,无需放入useCallback的依赖数组:
const updateCurrentTime = useCallback((aTime: number) => {
  playerRef.current?.audio.current?.currentTime = aTime;
}, []);
  1. 完整修正代码
import { useRef, useCallback } from 'react';
import H5AudioPlayer from 'react-h5-audio-player';

// 假设props类型已提前定义
const AudioPlayerWithTranscript = ({ playerProps, text }) => {
  const playerRef = useRef<H5AudioPlayer>(null);

  const updateCurrentTime = useCallback((aTime: number) => {
    playerRef.current?.audio.current?.currentTime = aTime;
  }, []);

  return (
    <div>
      <div>
        <H5AudioPlayer ref={playerRef} {...playerProps} />
      </div>
      <div>
        {text.map((aText, aIndex) => (
          <span 
            key={aIndex} 
            onClick={() => updateCurrentTime(aText.start)}>
            {aText.value}
          </span>
        ))}
      </div>
    </div>
  );
};

export default AudioPlayerWithTranscript;

错误原因说明

  • 你之前错误地将useRef泛型设为MutableRefObject<H5AudioPlayer>,但useRef<T>本身返回的就是MutableRefObject<T>,泛型参数只需传入实例类型H5AudioPlayer。
  • H5AudioPlayer实例原生包含audio: React.RefObject<HTMLAudioElement>属性,无需自定义接口,直接复用官方类型就能正确识别该属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:40:48