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", ()