我想使用youtube API(https://developers.google.com/youtube/iframe_api_reference)从附加视频中获取当前时间。而且我想在另一个组件中使用该信息,所以这就是为什么要给window对象赋予一个属性,以便可以在任何地方访问该信息的原因。

代码:

  import React from 'react';

    class VideoSingle extends React.Component {
      constructor(props){
        super(props);
        this.state = {}
      }

      componentDidMount() {
       // 2. This code loads the IFrame Player API code asynchronously.
       var tag = document.createElement('script');

       tag.src = "https://www.youtube.com/iframe_api";
       var firstScriptTag = document.getElementsByTagName('script')[0];
       firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

       // 3. This function creates an <iframe> (and YouTube player)
       //    after the API code downloads.

       var YT;
       window.onYouTubeIframeAPIReady = function() {
         YT = window.YT;
         window.player = new YT.Player('videoplayer', {
           height: '390',
           width: '640',
           videoId: 'M7lc1UVf-VE',
           origin:'http://localhost:3001',
           events: {

           }

         });

       }

      }

      componentDidUpdate() {

        console.log(window.player,'logging window.player at componentDidUpdate')
      }
      render(){

        console.log(window.player,'logging window.player at render')


      return (
       //1. The <iframe> (and video player) will replace this <div> tag.
        <div id="videoplayer"></div>

        );
      }
    };



export default VideoSingle;


我尝试使用console.log的所有位置都给出了“ undefined”(在我示例中console.log中记录在componentDidMount和render中):

javascript - 当console.logging组件内部的window对象时,它给出了“undefined”。但是使用浏览器控制台时可以访问-LMLPHP

但是,当我在浏览器控制台中输入window.player.getCurrentTime()时,我实际上得到了一个值

javascript - 当console.logging组件内部的window对象时,它给出了“undefined”。但是使用浏览器控制台时可以访问-LMLPHP

我想了解如何在我的应用程序中的任何地方访问window.player.getCurrentTime()。

应用程式回购:https://github.com/phelpa/YouList

最佳答案

登录后,YouTube脚本很可能会创建播放器...尝试呈现整个视图,然后创建控制台日志。在您的代码中...以下几行没有意义。检查YT API参考

YT = window.YT;


这使YT不确定...可能是您要说window.YT = YT吗?请仔细检查。祝你好运,保持联系。

关于javascript - 当console.logging组件内部的window对象时,它给出了“undefined”。但是使用浏览器控制台时可以访问,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53734345/

10-12 13:01