首页 > 解决方案 > 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>
         );
    }

标签: reactjsreact-propsreact-player

解决方案


TLDR:将您内部的功能更改为setTimeout箭头功能,它应该可以工作。

原因是在 in但不是 in 中this.props.lightBoxHandler定义的,是因为您在使用关键字声明的函数内部调用,而不是箭头函数。onEndedonDurationonDurationthis.propssetTimeoutfunction

箭头函数this在词法范围内使用。定义的函数function有自己的this.

请参阅:https ://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4


推荐阅读