只是想让这些视频在鼠标悬停时播放。我可以从控制台看到我需要创建一个函数而不是使用字符串(其他SO答案使用字符串),那么如何在不创建太多额外代码的情况下做到这一点?理想情况下,我希望在 onMouseOver 和 onMouseOut 属性上正确设置函数。
<video
poster="https://i.imgur.com/Us5ckqm.jpg"
onMouseOver="this.play()"
onMouseOut="this.pause();this.currentTime=0;"
src={`${vid.videos.tiny.url}#t=1`}
</video>
也尝试过
<video
poster="https://i.imgur.com/Us5ckqm.jpg"
onMouseOver={() => this.play()}
onMouseOut={() => this.pause()}
src={`${vid.videos.tiny.url}#t=1`} >
</video>
这给了我错误:无法读取未定义的属性“play”。
编辑 不确定这是否相关,但上面的代码位于 map 函数内部,该函数也是 get 请求的一部分。这是完整的功能:
const fetchVideos = async (amount, category) => {
const response = await axios.get('https://pixabay.com/api/videos/', {
params: {
key: '123456123456123456',
per_page: amount,
category: category
}
})
console.log(response)
const vidsAsHtml = response.data.hits.map(vid => {
return (
<div className={`${props.page}--grid-content-wrapper`} key={vid.picture_id}>
<div className={`${props.page}--grid-video`}>
<video className=".video"
poster="https://i.imgur.com/Us5ckqm.jpg"
onMouseOver={() => this.play()}
onMouseOut={() => this.pause()}
src={`${vid.videos.tiny.url}#t=1`} >
</video>
</div>
<div className={`${props.page}--grid-avatar-placeholder`}></div>
<div className={`${props.page}--grid-title`}>{vid.tags}</div>
<div className={`${props.page}--grid-author`}>{vid.user}</div>
<div className={`${props.page}--grid-views`}>{abbreviateNumbersOver999(vid.views)}
<span className={`${props.page}--grid-date`}> • 6 days ago</span>
</div>
</div>
)
})
setResource(vidsAsHtml)
}
编辑 2: 似乎其他人也有 'this' keyword is undefined inside Mapping Statement (React) 。尽管我尝试了这些解决方案,但“this”仍然未定义。
最佳答案
名为 Felix Kling 的用户给出了一个非常简单的答案,解决了我的问题this post :
Event handler props are expected to be passed a function. Currently you are trying to pass the return values of
this.play()
andthis.pause()
as event handlers, which wouldn't work anyway.Also React doesn't make the element available to the event handler via
this
, but you can access it viaevent.target
:<video poster="https://i.imgur.com/Us5ckqm.jpg" onMouseOver={event => event.target.play()} onMouseOut={event => event.target.pause()} src={`${vid.videos.tiny.url}#t=1`} > </video>
查找工作解决方案 here.
关于javascript - 在 React 中使用 JS 在 mouseOver 上播放视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59207298/