渲染前如何获取React组件的大小(高度/宽度)? [英] How to get a react component's size (height/width) before render?

查看:2129
本文介绍了渲染前如何获取React组件的大小(高度/宽度)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个react组件,需要在其呈现之前提前知道其尺寸.

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

当我在jquery中制作小部件时,我可以只$('#container').width()并在构建组件时提前获取容器的宽度.

When I'd make a widget in jquery I could just $('#container').width() and get the width of the container ahead of time when I build my component.

<div id='container'></div>

这些容器的尺寸以及页面上的许多其他容器均在CSS中定义.谁在React中定义组件的高度,宽度和位置?我已经习惯了CSS并能够访问它.但是在React中,似乎我只能在组件渲染后才能访问该信息.

these container's dimensions are defined in CSS, along with a bunch of other containers on the page. who defines the height and width and placement of the components in React? I'm used to CSS doing that and being able to access that. But in React it seems I can only access that information after the component has rendered.

推荐答案

如前所述,在将元素呈现为DOM之前,您无法获得任何元素的尺寸.在React中,您可以做的只是渲染一个容器元素,然后在componentDidMount中获取其大小,然后渲染其余内容.

As it was already mentioned, you can't get any element's dimensions until it is rendered to DOM. What you can do in React is to render only a container element, then get it's size in componentDidMount, and then render rest of the content.

我做了一个工作示例.

请注意,在componentDidMount中使用setState是一种反模式,但在这种情况下就可以了,因为这正是我们要实现的目标.

Please note that using setState in componentDidMount is an anti-pattern but in this case is fine, as it is exactly what are we trying to achieve.

干杯!

代码:

import React, { Component } from 'react';

export default class Example extends Component {
  state = {
    dimensions: null,
  };

  componentDidMount() {
    this.setState({
      dimensions: {
        width: this.container.offsetWidth,
        height: this.container.offsetHeight,
      },
    });
  }

  renderContent() {
    const { dimensions } = this.state;

    return (
      <div>
        width: {dimensions.width}
        <br />
        height: {dimensions.height}
      </div>
    );
  }

  render() {
    const { dimensions } = this.state;

    return (
      <div className="Hello" ref={el => (this.container = el)}>
        {dimensions && this.renderContent()}
      </div>
    );
  }
}

这篇关于渲染前如何获取React组件的大小(高度/宽度)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆