gpt4 book ai didi

javascript - 为什么在 React componentDidMount 中获取不到 DOMNode 的样式(scrollHeight)?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:56:53 25 4
gpt4 key购买 nike

我正在开发一个 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 值。似乎 chrome 的速度不够快,无法在执行 findDOMNode 时完全呈现 DOMNode。

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

感谢您的耐心解答!

最佳答案

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;

关于javascript - 为什么在 React componentDidMount 中获取不到 DOMNode 的样式(scrollHeight)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38387609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com