【问题标题】:Why can't I get the DOMNode's style (scrollHeight) in the React componentDidMount?为什么我在 React componentDidMount 中获取不到 DOMNode 的样式(scrollHeight)?
【发布时间】:2016-11-18 03:53:34
【问题描述】:

我正在开发一个 React 应用程序并尝试获取 DOM 元素的计算样式“scrollHeight”。

我把这段代码放在componentDidMount中:

componentDidMount() {

        // let _this = this;
        // window.onload = function(){


        let imgFigureDOM = findDOMNode(_this.refs.imgFigure0),
            imgW = imgFigureDOM.scrollWidth,
            imgH = imgFigureDOM.scrollHeight;
        // }
   }

但是,我只能在chrome浏览器中获得正确的scrollHeight值。执行findDOMNode时似乎chrome不够快,无法完全渲染DOMNode。

如上使用window.onload时值是正确的,但是componentDidMount执行时DOMNode不应该完全加载吗?

感谢您的耐心解答!

【问题讨论】:

  • 我并不感到惊讶,附加到 DOM 的元素与完全渲染的元素不同

标签: javascript reactjs browser


【解决方案1】:

componentDidMount() 在渲染 React 组件时调用。 React 已经渲染了一个<img> 标签,这并不意味着图像已经加载。

让我们设置一些基本定义来区分渲染和加载:

  • 已渲染:React 已将您的虚拟 DOM 元素(在渲染方法中指定)转换为真实的 DOM 元素并将它们附加到 DOM。

  • 已加载:图像数据或其他远程内容已完全下载(或下载失败)。

因此,只需将 onLoad 和 onError 事件处理程序添加到您的 React <img> 标记,然后就可以了。 image-events

简短示例:

import React from 'react';

class ImageWithStatusText extends React.Component {
  constructor(props) {
  super(props);
  this.state = { imageStatus: null };
}

handleImageLoaded(e){
  this.setState({ imageStatus: 'loaded' });
  console.log(e.target.scrollHeight);
}

handleImageErrored() {
  this.setState({ imageStatus: 'failed to load' });
}

render() {
  return (
    <div>
      <img
        src={this.props.imageUrl}
        onLoad={this.handleImageLoaded.bind(this)}
        onError={this.handleImageErrored.bind(this)}
      />
      {this.state.imageStatus}
    </div>
  );
 }
}
export default ImageWithStatusText;

【讨论】:

  • 非常感谢!我认为渲染意味着加载是理所当然的。例子有助于进一步理解:)
猜你喜欢
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 2019-05-08
  • 2019-04-17
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 2019-03-19
相关资源
最近更新 更多