reactjs - TypeError:无法读取未定义的属性“lightBoxHandler”
问题描述
视频播放完毕后,我正在尝试自动关闭灯箱。
onEnded
属性在 99.99% 的时间里都很好用,但有时它不会触发回调。所以我尝试使用onDuration
.
上述错误发生在设置为的回调中onDuration
。控制台打印持续时间很好,但我不确定为什么它无法识别以下方法并抛出错误。this.props.lightBoxHandler(this.props.entry.type);
renderEntry() {
if (this.props.entry.type === "photo") {
this.disableLightbox();
return <img alt={Math.random()} src={this.props.entry.entry} onClick={ () => this.props.lightBoxHandler(this.props.entry.type)} />
}
if (this.props.entry.type === "video") {
return <ReactPlayer
url={this.props.entry.entry}
className='react-player'
playing={true}
width='100%'
height='100%'
onEnded={() => this.props.lightBoxHandler(this.props.entry.type)}
onDuration={(duration) => {
console.log("Duration " + duration);
setTimeout(function () {
this.props.lightBoxHandler(this.props.entry.type);
}, duration*1000) }}
/>
}
}
render() {
let classList = this.props.entry.is === true ? "lightbox-wrapper active" : "lightbox-wrapper";
return (
<React.Fragment>
<div className={classList}>
{this.renderEntry()}
</div>
</React.Fragment>
);
}
解决方案
TLDR:将您内部的功能更改为setTimeout
箭头功能,它应该可以工作。
原因是在 in但不是 in 中this.props.lightBoxHandler
定义的,是因为您在使用关键字声明的函数内部调用,而不是箭头函数。onEnded
onDuration
onDuration
this.props
setTimeout
function
箭头函数this
在词法范围内使用。定义的函数function
有自己的this
.
请参阅:https ://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4
推荐阅读
- python - 如何从布尔值的 Pandas DataFrame 创建频率分布矩阵
- function - 将函数值作为字典中的值返回
- google-apps-script - “在 retriveFormData 时未捕获”错误,即使没有参考我的第一个文档调用
- python - 如何使用 Flask 在 Python 中每 5 秒更新一次 RSS Feed
- reactjs - 单击按钮获取值
- c++ - 使用 libcurl 进行批量 url 提交的正确 BING Api POST url 是什么?
- reactjs - Next.js 的assetPrefix 破坏了更少的加载器
- java - Java SWT windowbuilder - 导出到可运行 jar 时不显示图像
- java - 不兼容的类型:将整数流转换为字符串流时 lambda 表达式中的返回类型错误?
- c# - 如何在 c# wfp 中垂直移动图像