2017-02-28 191 views
2

当我用reactjs编写web应用程序时,我想在目标div容器内创建视频播放器。在reactjs应用程序中,如何获得dom元素的正确宽度?

所以,我编写的“componentDidMount”功能,像这样:

componentDidMount(){ 

    const box = document.getElementById('video-box'); 

    //use the ThirdPartyObject player API to create the player 

    player = ThirdPartyObject('#video-box').videoPlayer({ 
     'width':box.clientWidth, 
     'height':box.clientWidth * 9/16, 
     'vid' : vid, 
     'df': '1' 
    }); 

} 

但是,实际上,我得到了球员比实际框更宽。如下:

1

所以,我测试的代码“document.body.clientWidth”中铬的控制台时的页面令人耳目一新。起初,结果是1440,但最后数字变成了1423.

那么,为什么呢?我该如何做正确的事情?

回答

0

,当我做了一些实验,如下:

componentDidMount(){ 

    const box = document.getElementById('video-box'); 

    //use the ThirdPartyObject player API to create the player 

    console.log('before player init: ' + box.clientWidth) 
    player = ThirdPartyObject('#video-box').videoPlayer({ 
     'width':box.clientWidth, 
     'height':box.clientWidth * 9/16, 
     'vid' : vid, 
     'df': '1' 
    }); 
    console.log('after player init: ' + box.clientWidth) 

} 

我喜欢,只是播放器初始化后,输出宽度是正确的。 我改变了玩家的风格,使其工作。虽然我知道这不是完美的方式。

componentDidMount(){ 

    const box = document.getElementById('video-box'); 

    //use the ThirdPartyObject player API to create the player 

    console.log('before player init: ' + box.clientWidth) 
    player = ThirdPartyObject('#video-box').videoPlayer({ 
     'width':box.clientWidth, 
     'height':box.clientWidth * 9/16, 
     'vid' : vid, 
     'df': '1' 
    }); 
    player.style.width = box.clientWidth 
    player.style.height = box.clientWidth *9 /16 

}