如何使用 ReactJS 监听 iframe keydown 事件

How to listen iframe keydown event with ReactJS

我想在 reactjs 中监听 iframe 的 keydown 事件。在我的 iframe 中,我嵌入了视频。现在,当视频正在播放时,我想处理键盘 events.Can 任何人请帮助我如何监听键盘事件。这是我的代码

class VideoDetail extends Component {

videoLoad(e) {
    console.log('videoLoaded');
    this.videoFrame.addEventListener('keydown',this.onVideoDown);
}

onVideoDown(e) {
    console.log('key pressed'); // This is not invoking
}

componentDidMount() {
    console.log(this.videoFrame);
}
render() {
    const video = this.props.video;
    if (!video) {
        return <div>Loading...</div>;
    }

    const videoId = video.id.videoId;
    const url = `https://www.youtube.com/embed/${videoId}`;
    return (
        <div className="video-detail col-md-8">
            <div className="embed-responsive embed-responsive-16by9">
                <iframe ref={(iframe) => { this.videoFrame = iframe; console.log(iframe); }} className="embed-responsive-item" src={url} onLoad={(e) => this.videoLoad(e)}></iframe>
            </div>
            <div className="details">
                <div>{video.snippet.title}</div>
                <div>{video.snippet.description}</div>
            </div>
        </div>
    );
}

}

您可以通过 iframe.contentWindow.document 捕获 iframe keydown 事件,如下所示,使用 e.targetthis.videoFrameref

修改后的代码

videoLoad(e) {
    console.log('videoLoaded');
    var iframe = e.target; // it is equal to "this.videoFrame" and so, you can avoid using "ref"
    //this.videoFrame.addEventListener('keydown',this.onVideoDown);
    iframe.contentWindow.document.addEventListener('keydown', this.onVideoDown);
}