【问题标题】:Convert document.querySelector() into Reactjs将 document.querySelector() 转换为 Reactjs
【发布时间】:2018-09-25 07:38:02
【问题描述】:

我正在尝试将下面的代码转换为 Reactjs。我使用下面的代码将 THEOplayer 嵌入到我的网站,只要我知道我们可以使用“ref”来替换 document.querySelector('.classname') 而不是针对特定的 DOM 来更改或修改它,但我仍然困惑并出现错误,以下更改我的代码的最佳做法是什么。

var playerConfig = {
    "libraryLocation": "//cdn.theoplayer.com/dash/theoplayer/",
    ui: {
        fluid: true
    },
};

var element = document.querySelector('.video-container');
var player = new THEOplayer.Player(element, playerConfig);

player.source = {
    sources : [{
        src : '//cdn.theoplayer.com/video/big_buck_bunny/big_buck_bunny.m3u8', // sets HLS source //  //cdn.theoplayer.com/video/star_wars_episode_vii-the_force_awakens_official_comic-con_2015_reel_(2015)/index.m3u8
        type : 'application/x-mpegurl' // sets type to HLS
    }],
    textTracks : [{
        default: true, //optional
        kind : 'subtitles',
        src : 'example.srt',
        srclang : 'en'
    }]
};


player.addEventListener('sourcechange', function() {
    player.removeEventListener('playing', firstplay);
    player.addEventListener('playing', firstplay);
});

【问题讨论】:

  • 请至少提供你的反应代码来说明你的尝试和你得到的错误(或制作一个代码 sn-p 来说明你的问题)

标签: javascript reactjs


【解决方案1】:

您可以简单地编写一个反应组件并在 componentDidMount 方法中添加您的自定义事件侦听器

const playerConfig = {
    "libraryLocation": "//cdn.theoplayer.com/dash/theoplayer/",
    ui: {
        fluid: true
    },
};

class App extends React.Component {
    componentDidMount() {
        const player = this.player;
        player.addEventListener('sourcechange',() => {
            player.removeEventListener('playing', this.firstplay);
            player.addEventListener('playing', this.firstplay);
        });
        this.playerSrc = new THEOplayer.Player(player, playerConfig);

        this.playerSrc.source = {
            sources : [{
                src : '//cdn.theoplayer.com/video/big_buck_bunny/big_buck_bunny.m3u8', // sets HLS source //  //cdn.theoplayer.com/video/star_wars_episode_vii-the_force_awakens_official_comic-con_2015_reel_(2015)/index.m3u8
                type : 'application/x-mpegurl' // sets type to HLS
            }],
            textTracks : [{
                default: true, //optional
                kind : 'subtitles',
                src : 'example.srt',
                srclang : 'en'
            }]
        };

    }
    render() {
       return <div className={video-container} ref={(ref) => this.player = ref}/>
    }
}

【讨论】:

    猜你喜欢
    • 2019-12-02
    • 2019-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2022-01-06
    • 2018-07-06
    相关资源
    最近更新 更多