0

在 react.js 中,下面的代码应该根据第 6 行提供给函数的数字显示本地图像一定次数。在实际程序中,该数字将根据从远程服务器获取的信息而改变,所以我不能只是硬编码它。

第 22 行调用图像的次数是正确的,但它显示的是替代文本而不是实际照片。

第 23 行完美地调用了图像。所以,我知道它被正确导入。

如何让第 22 行显示图像而不仅仅是文本?

import React from 'react'
import local_image from '../images/local_image.png'

export default class Album extends React.Component {

  displayXImages(num) { // line 6
    let x = 0
    let img_html = ''
    while (x < num) {
      img_html = img_html + "<img src={local_image.png} alt='local image' className='image' />" // line 10
      x = x + 1
    }
    
    return img_html // line 14
  }

  render() {
    const inner_html = displayXImages(3) // line 18

    return(
      <main>
        <div className='album' dangerouslySetInnerHTML={inner_html) /> // line 22
        <img src={local_image.png} alt='local image' className='image' /> // line 23
      </main>
    )
  }
}
4

1 回答 1

1

更新#1:

import React from "react";
import local_image from '../images/local_image.png'

export default class Album extends React.Component {
  displayXImages(num) {
    // line 6
    let x = 0;
    let img_html = "";
    while (x < num) {
      img_html =
        img_html +
        `<img src=${local_image} alt='local image' className='image' />`; // EDITED: Template literal string with local_image being casted to its value
      x = x + 1;
    }

    return { __html: img_html }; // EDIT: dangeruslySetInnerHTML accepts an object type containing __htmo prop that should hold ur HTML content
  }

  render() {
    const inner_html = this.displayXImages(3); // line 18
    
    return (
      <main>
        <div className="album" dangerouslySetInnerHTML={inner_html} />
      </main>
    );
  }
}

不同的方法:

我利用 Refs 制作了这个简单的应用程序。它应该转化为您的需求。

import React from 'react'

export default class Album extends React.Component {
  constructor(props) {
    super(props);
    this.imageContainer = React.createRef();
  }

  setImageContainerContent() {
    const imgSRC = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/React.svg/250px-React.svg.png";
    if(this.imageContainer.current) {
      const newImgEl = document.createElement("img");
      newImgEl.src = imgSRC;
      newImgEl.alt = "Some image alt text"
      /*
       * would you remove everything else from the tree with every update??
       * if u shall >> this.imageContainer.current.innerHTML = "";
       *
       */
      this.imageContainer.current.appendChild(newImgEl);
    }
  }

  componentDidMount() {
    this.setImageContainerContent();
  }

  render() {
    return(
      <main>
        <div className='album' ref={this.imageContainer} />
      </main>
    )
  }
}
于 2021-09-25T20:58:13.210 回答