简体   繁体   中英

In reactjs app, how can I get the right width of a dom element?

When I wrote a web app with reactjs, I wanted to create video player within a target div container.

So, I coded in the 'componentDidMount' function ,like this:

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'
    });

}

But , actually, I got the player wider than the actual box. As follow:

1

So, I tested the code 'document.body.clientWidth' in the console of chrome when the page was refreshing. At first, the result was 1440, but at last the number changed to 1423.

So, why is that? How can I do the right thing?

when I do some experiment, as follow:

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)

}

I fond that just after the player init , the output width is the correct one. I change the style of the player to make it work. Though I know it is not the perfect way.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM