javascript - 在reactjs应用程序中,如何获得dom元素的正确宽度?

标签 javascript html reactjs

当我使用 ReactJS 编写 Web 应用程序时,我想在目标 div 容器中创建视频播放器。

因此,我在“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

所以,我在页面刷新时在chrome的控制台中测试了代码“document.body.clientWidth”。一开始结果是1440,最后变成了1423。

那么,这是为什么呢?我怎样才能做正确的事?

最佳答案

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

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

}

关于javascript - 在reactjs应用程序中,如何获得dom元素的正确宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42505056/

相关文章:

javascript - Jquery扩展深拷贝

javascript - 在 Google Gears Workerpool 中加密 JSON

javascript - 样式化选择框

javascript - 链接并滚动到部分

javascript - 如何使用 RequireJS 实现工厂设计模式?

javascript - 对 XMLHTTPRequest 的回退支持

javascript - 从 Angular Controller 控制 SoundCloud js sdk

javascript - React - 将函数传递给子组件什么都不做

javascript - 在 React 中传递 onFocus 事件的参数

css - 使用 webpack 生成的标识符定位 React 中的样式化组件?