0

我根本不知道cdn文件夹上有多少图像,所以每当我得到图像错误时我都会循环我将停止添加图像标签。但即使是(作为变量)更改为真正循环的循环也会循环到 13,而不是超过 10,因为文件夹中只有 10 张图像。我还想为每个添加弹出窗口,因此添加 num 但仅在图像上附加最后一个索引。

componentDidMount() {
    let images = [];
    let src = [];
    var a = false;
    let commonPath = filesPath + "companyImages/";
    let num = 1;
    let companyId = this.props.tab.Id;
    while (a !== true && num < 13) {
        if (a == true) {
            alert("I am breaking")
            break;
        }
        let imageFolder = `${companyId}/${companyId}_00${num}.jpg`;
        let fullPath = `${commonPath}${imageFolder}`;
        let tag = <img src={fullPath} height={140} key={num} id={'image' + num} width={200} className="image" onClick={() => this.openImage(num)} onError={a = true} onLoad={() => { console.log(num,"yup")}}></img>;
       
        images.push(tag);
        src.push(fullPath);
        num++;

    }
   
    this.setState({allImages:images,allSrcs:src});
}
4

1 回答 1

2

怎么样

const images = [];
const imageLoad = () => {
  const img = new Image();
  let imageFolder = `${companyId}/${companyId}_00${images.length}.jpg`;
  let fullPath = `${commonPath}${imageFolder}`;
  img.addEventListener('load',() => {
    images.push(img.src);
    imageLoad();
  })
  img.addEventListener('error',() => {
    images.map((img,i) => `<img src="${img.src}" data-key="${num}$ id="image${i} className="image"/>`);
    // add the images to the DOM here
  }
  img.src=fullPath;       
};
imageLoad()

然后委托点击并在CSS中设置高度和宽度

于 2021-08-21T15:29:25.697 回答