加载时渲染错误的图像

时间:2019-06-11 23:01:53

标签: reactjs

我正在尝试将图像列表插入我的网页。我能够成功执行此操作,但是在页面上显示它们时遇到了问题。我正在使用react-grid-gallery package来显示图像。在此程序包中,您需要首先设置缩略图的高度和宽度。这给我造成了一个问题,因为每个图像的高度和宽度都不同。我想要的是使用Javascript确定每个图像的高度和宽度,并将它们动态设置为关联的图像。

我对React不太熟悉,所以我尝试更改声明图像大小的位置。我在componentDidMount,构造函数等中设置了图像大小,但没有任何效果。

constructor(props) {
    super(props);

    this.state = { stills: STILLS, val: 4 };

    this.setImgSize = this.setImgSize.bind(this);

    this.state.stills.map( (image, index) => {
      this.setImgSize(image, index);
    })
  }


setImgSize(image, index) {

    var newImg = new Image();

    newImg.onload = (function() {
      console.log("Onload");

      this.setState(state => {
        const stills = state.stills.map((still, id) => {
          if (id === index) {
            still.thumbnailHeight = newImg.height;
            still.thumbnailWidth = newImg.width;
          }
        })
      });
    }).bind(this);

    newImg.src = image.src; // this must be done AFTER setting onload
  }

图像最初以我设置的尺寸显示,但是在离开页面然后导航回页面之后,图像尺寸正确。

1 个答案:

答案 0 :(得分:1)

反应构造器不是执行异步操作的最佳位置。

'onload'方法是异步的-因此需要等待直到它返回结果。您可以通过使用Promise来实现结果-并在componentDidMount生命周期方法中移动整个功能。

我在react-grid-gallery的“ quick anddirty”示例中修改了代码,以读取图像缩略图的宽度和高度属性。

setImgSize = (  image )=> {
    const promise = new Promise( function(resolve, reject) {

     let img = new Image();
     img.src = image.thumbnail;
     img.onload =  () => {
         // Should see width and height of images
         console.log( 'imge src', img.src, 'width ' , img.width, 'height', img.height);
         image.thumbnailHeight = img.height;
         image.thumbnailWidth = img.width;
         resolve('ok');               
          }

   });
   return promise;
}



componentDidMount() {
      Promise.all(this.IMAGES.map(this.setImgSize)).then(  (result) => { 
        //console.log('before state', result);
        this.setState({loading: false});
        console.log('after loop');
         }, function (error) {
               console.log('error ', error);
       });

}

这是codesandbox中的完整代码: https://codesandbox.io/s/react-grid-gallery-ztf4n?fontsize=14

相关问题