[英]React.js - removeEvent() in useEffect() hook
I'm trying to get the HTML5 audio element to autoplay on page load.我正在尝试让 HTML5 音频元素在页面加载时自动播放。 I know that Chrome doesn't allow autoplay by default, unless something triggers it.
我知道 Chrome 默认情况下不允许自动播放,除非有什么触发它。 So I've created a couple of event listeners within the
useEffect()
hook:所以我在
useEffect()
钩子中创建了几个事件监听器:
const Audio = () => {
const audioPlayer = document.getElementById('myAudio')
const playAudio = () => audioPlayer.play()
useEffect(() => {
window.addEventListener('scroll', playAudio)
window.addEventListener('mousemove', playAudio)
return () => {
window.removeEventListener('scroll', playAudio)
window.removeEventListener('mousemove', playAudio)
}
}, [])
return (
<audio
id="myAudio"
src={ audioAssetHere }
/>
)
}
This does work but it keeps playing every time the cursor moves.这确实有效,但每次 cursor 移动时它都会继续播放。 I only want it to play once.
我只希望它播放一次。 I also get this error in the console:
我也在控制台中收到此错误:
DOMException: play() failed because the user didn't interact with the document first
And yet the audio still works every time the cursor moves.然而,每次 cursor 移动时,音频仍然有效。
I also tried using useRef
and assign it to the audio tag ref={audioRef}
, and then used it within the useEffect
hook:我还尝试使用
useRef
并将其分配给音频标签ref={audioRef}
,然后在useEffect
挂钩中使用它:
const audioRef = useRef()
const playAudio = () => audioRef.current.play()
useEffect(() => {
window.addEventListener('scroll', playAudio)
window.addEventListener('mousemove', playAudio)
return () => {
window.removeEventListener('scroll', playAudio)
window.removeEventListener('mousemove', playAudio)
}
}, [])
This gives the error:这给出了错误:
TypeError: audioRef.current.play is not a function
So in a nutshell, what I want is the audio to play every time the page loads.所以简而言之,我想要的是每次页面加载时播放的音频。 And I only want it to play once.
我只希望它播放一次。
Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks
谢谢
you are trying to play audio on every mousemove/scroll event, instead of it you just need to play it once on the first mousemove/scroll event:您正在尝试在每个 mousemove/scroll 事件上播放音频,而不是它,您只需要在第一个 mousemove/scroll 事件上播放一次:
const Audio = () => {
const audioRef = React.useRef();
useEffect(() => {
const playAudio = () => {
audioRef.current.play();
removeListeners()
}
window.addEventListener('scroll', playAudio)
window.addEventListener('mousemove', playAudio)
const removeListeners = () => {
window.removeEventListener('scroll', playAudio)
window.removeEventListener('mousemove', playAudio)
}
return () => {
removeListeners()
}
}, [])
return (
<audio
src={ audioAssetHere }
ref={ audioRef }
/>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.