How to get a react component's size (height/width) before render?

前端 未结 6 1216
天命终不由人
天命终不由人 2020-12-03 00:22

I have a react component that needs to know its dimensions ahead of time, before it renders itself.

When I\'d make a widget in jquery I could just <

6条回答
  •  一向
    一向 (楼主)
    2020-12-03 01:21

    You cannot. Not reliably, anyway. This is a limitation of browser behavior in general, not React.

    When you call $('#container').width(), you are querying the width of an element that has rendered in the DOM. Even in jQuery you can't get around this.

    If you absolutely need an element's width before it renders, you will need to estimate it. If you need to measure before being visible you can do so while applying visibility: hidden, or render it somewhere discretely on the page then moving it after measurement.

提交回复
热议问题