【问题标题】:How to use get the height of parent div of a img tag in React?如何在 React 中使用获取 img 标签的父 div 的高度?
【发布时间】:2019-01-12 03:12:28
【问题描述】:

我正在使用带有 React.js 的 html 画布。我想将我的画布高度设置为等于正文的高度,以便人们可以在整个页面上绘制。

import IMG from "../../assets/img/contact-img.jpg";
 constructor(props){
        super(props);
        this.state ={
            width:0,
            height:0
        }
    }
componentDidMount(){
    let newState = {
        width:this.myRef.current.getBoundingClientRect().width,
        height:this.myRef.current.getBoundingClientRect().height
    };
    this.setState(newState);

}
render(){

        <div>
            <DrawableCanvas width={this.state.width} height={this.state.height}/>
            <img src={IMG} />
        </div>

}

我的想法是先画一个画布(width,height=0)。整个布局组件渲染完成后,我们可以获取布局的高度并更新画布。

问题是当有子标签时我无法正确获取高度。 但我成功地在 Chrome 控制台中获得了高度。似乎 React 在渲染组件时,标签被忽略了。

【问题讨论】:

  • 您是在寻找设备高度,还是画布父元素的高度?您在问题中都提到了两者。
  • @Douglas 您能告诉我们您如何处理DrawableCanvas 组件中的维度属性吗?

标签: javascript html height getboundingclientrect


【解决方案1】:

请查看https://www.javascriptstuff.com/detect-image-load/

在 react 中,渲染和加载是有区别的。
我试图在 componentDidMount() 中获取宽度和高度,这是错误的。
因为此时,所有的&lt;img&gt;都没有被加载。

要解决这个问题,请看https://www.javascriptstuff.com/react-image-gallery/

这个例子展示了当&lt;img&gt;使用&lt;img onLoad={Fn} onError={Fn}&gt;加载时如何做一些事情(在我的例子中,获取宽度和高度)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多