可以通过在组件中使用state来计算并更新图片的高度,代码示例:

import React, { Component } from 'react';

class ImgComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      width: 0,
      height: 0,
    };
    this.handleResize = this.handleResize.bind(this);
  }

  componentDidMount() {
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }

  handleResize() {
    const width = this.imgRef.clientWidth;
    const height = width / 2;
    this.setState({ width, height });
  }

  render() {
    const { src } = this.props;
    const { width, height } = this.state;
    return (
      <img
        ref={(ref) => { this.imgRef = ref; }}
        src={src}
        style={{ width: `${width}px`, height: `${height}px` }}
      />
    );
  }
}

export default ImgComponent;

在组件中使用state来保存图片的宽度和高度,并在组件挂载时使用componentDidMount方法计算初始值和添加监听器,在组件卸载时移除监听器。同时,使用ref来获取图片元素的引用并在handleResize方法中计算高度,最后在render方法中将图片的宽度和高度设置为state中保存的值

reactjs img 高度通过计算获得结果为宽度的一半

原文地址: https://www.cveoy.top/t/topic/g66t 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录