利用 useRef
获取 audio
标签的 DOM 节点并操作.
示例
如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import { useState, useRef } from 'react';
const AudioPlayer = () => { const [isPlaying, setIsPlaying] = useState(false); const audioRef = useRef(null);
function handleClick() { if (audioRef.current.paused) { setIsPlaying(true); audioRef.current.play() } else { setIsPlaying(false); audioRef.current.pause() } }
return ( <div className="audio-player"> <audio ref={audioRef}> <source src="/music/test.mp3" type="audio/mpeg" /> </audio> <button type="button" onClick={handleClick}> { isPlaying ? "pause" : "play" } </button> </div> ); }
export default AudioPlayer
|
这里涉及一些常用操作:
- 查看当前 audio 是否播放
ref.current.paused
- audio 播放
ref.current.play()
- audio 暂停
ref.current.pause()