首页 > 解决方案 > 如何使用 img.src 构造渲染函数

问题描述

我的render()函数中有以下代码,并且每当发生状态更改时,我都会尝试动态更改图像的高度和宽度:

render() {

    const imageURL = photos[this.state.currentImage].url;

    const base_image = new Image();
    base_image.src = imageURL;

    var wrh = base_image.width / base_image.height;
    var newWidth = 600;
    var newHeight = newWidth / wrh;

    return (

       <img height={newHeight} width={newWidth}>
    )

}

我知道我必须添加一个base_image.onload函数来确保何时base_image.src设置图像开始加载,但代码跳转到return()并呈现错误heightwidth值的图像,因为图像没有完成加载并且我没有获取正确的值。base_image如何构建我的代码,以便在完成加载之前不会渲染图像?

标签: javascriptreactjs

解决方案


您可以使用 astate variable来存储图像的比率。在该render方法中,您可以使用条件渲染来防止显示图像,直到计算出比率

const width = 600;

class YourComponent {
  constructor(props) {
    super(props);
    this.state = {
      ratio: undefined,
      currentImage: 0
    };
    this.image = new Image();
  }

  componentDidMount() {
    this.img.onload = () => {
      this.setState({
        ratio: this.img.naturalWidth / this.img.naturalHeight  
      });
    };
    this.img.src = photos[this.state.currentImage].url;
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.currentImage !== prevState.currentImage) {
      this.img.src = photos[this.state.currentImage].url;
    }
  }

  render() {
    const {ratio} = this.state;
    return ratio && <img width={width} height={width/ratio}>;
  }
}

推荐阅读