react+typescript使用ref实现自定义的audio标签

react+typescript使用ref实现自定义的audio标签

react+ts比较严格,一般的ref会一直提示没有这个属性,一定都要声明后才能使用

标签上的ref要用大括号的形式:

<audio ref={
   this.audio} src={
   url} controls>
   你的浏览器不支持音频播放哦!(;´༎ຶД༎ຶ`)
</audio>

在class里面的最外侧定义audio的类型

audio: React.RefObject<any>;

然后在constructor这个生命周期中创建ref句柄

this.audio = React.createRef();

打印一下this.audio:

  componentDidMount() {
   
    console.log(this.audio);
  }

打印结果
会发现有一个current的属性,所有原生js的方法和属性全都在这个属性里面,所以我们要进行原生的js操作要加上这个属性,否则会为空:

this.audio.current.play();

以上就是基本的技术点,下面进入demo

html结构:进度条外框outer包裹着进度条内核inner

<div
   className="outer"
   ref={
   this.outer}
   onTouchMove={
   e => this.audioX(e)}
   onTouchStart={
   e => this.audioX(e)}
   >
     <div className="inner" ref={
   this.inner}>
         <div className="innerBtn"></div>
     </div>
</div>

css样式如下:

.outer{
   
    width: 500px;
    height:10px;
    background-color: black;
    border-radius: 5px;
}
.inner{
   
    position: relative;
    width: 0;
    height:10px;
    background-color: red;
    border-radius: 5px;
}
.innerBtn{
   
    position: absolute;
    width: 20px;
    height: 20px;
    top:-5px;
    right: -5px;
    border-radius: 50%;
    background: blue;
}

然后使用audio标签自带的方法和属性
this.audio.current.duration音频总时长
this.audio.current.currentTime当前播放到的时长
this.audio.current.playbackRate音频播放速度

this.audio.current.play();开始播放
this.audio.current.pause();暂停
this.audio.current.οncanplay=()=>{ } 当音频可以播放时执行
this.audio.current.οnwaiting=()=>{ } 当音频在缓冲时执行
this.audio.current.οntimeupdate=()=>{ } 当播放时间变动时(播放中)执行

监听audio的事件

 handleAudio() {
   
    let audio = this.audio.current;
    // timeupdate,播放位置改变时触发
    audio.addEventListener("timeupdate", () => {
   
      console.log("播放位置改变");
    });
    // canplay,表示音频可以播放了,准备就绪
    audio.addEventListener("canplay", () => {
   
      console.log("可以播放了");
    });
    // progress,音频在加载或缓冲
    audio.addEventListener("progress", () => {
   
      console.log("音频在加载或缓冲");
    });
    // waiting,需要缓冲下一帧而停止播放时触发
    audio.addEventListener("waiting", () 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值