📜  页面关闭时停止播放音乐反应 - Javascript代码示例

📅  最后修改于: 2022-03-11 15:02:57.002000             🧑  作者: Mango

代码示例1
import React, { useRef, useEffect } from 'react';
import waves from '../audio/waves.mp3';
    
const RockyCoast = (props) => {
    // the audio variable needs to be stored in a ref in order to access it across renders
    let audio = useRef();
    // start the audio (using the .current property of the ref we just created) when the component mounts using the useEffect hook
    useEffect(() => {
        audio.current = new Audio(waves)
        audio.current.play()
    }, [])
    // Stop the audio when the component unmounts
    // (not exactly what you asked re React Router, but similar idea)
    useEffect(() => {
        return () => {
            audio.current.pause()
            console.log("in cleanup")
        }
    }, [])
    ...

    return (
        <>
            ...
        
    )
}
export default RockyCoast;