【问题标题】:React select div height when DOM is loaded加载DOM时反应选择div高度
【发布时间】:2020-02-06 23:17:27
【问题描述】:

我在选择“隐藏”选项卡中加载的图表时正确地显示了React Plotly的问题。似乎这是一个已知问题,除了默认选项卡之外的每个选项卡都不会适当地调整大小,因为它不知道隐藏图的尺寸。

为了解决这个问题,我想动态更新选项卡高度,使其等于默认选项卡的高度。像这样的东西:Change div height when tab is selected

问题是,我无法在 DOM 加载时选择选项卡高度值。我想我可以添加一个带有 evenlistener 的 componentDidMount 函数来进行窗口加载,如下所示:

    constructor(props) {
        super(props)
        this.state = {
            value: 0
        };
        this.handleLoad = this.handleLoad.bind(this);
    }

    componentDidMount() {
        window.addEventListener('load', this.handleLoad);
    }

    handleLoad() {
        console.log("firstTab height: " + $('#firstTab').offsetHeight)
    }

这个问题是,控制台日志输出firstTab height: undefined。

当我检查网页并将命令 $('#firstTab').offsetHeight 放入控制台时,我能够得出 697 像素的高度。

我不想硬编码标签像素大小。谁能指导我为什么我无法在窗口加载时获取元素高度?

【问题讨论】:

    标签: css reactjs window-load


    【解决方案1】:

    尝试使用 clientHeight 属性。

    componentDidMount() {
        const height = document.getElementById('firstTab').clientHeight;
    }
    

    【讨论】:

      【解决方案2】:

      我认为你可以做这样的事情,而不是使用事件监听器。

      componentDidMount() {
          const height = this.firstTab.clientHeight;
          console.log(height) // => gives you height
      }
      
      render() {
          return (
            <div 
              id="firstTab"
              ref={ (firsTabElement) => { this.divElement = firstTabElement } }
            >
              Tab Content
            </div>
          )
        }
      

      如果您没有隐藏或设置任何条件以从 DOM 中删除 firstTab,则在第一次渲染之后。它将在 componentDidMount 生命周期中提供给您。

      【讨论】:

        猜你喜欢
        • 2021-07-20
        • 2020-06-21
        • 1970-01-01
        • 1970-01-01
        • 2014-03-26
        • 1970-01-01
        • 2011-11-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多