【问题标题】:dynamic import of images react动态导入图片 react
【发布时间】:2020-04-27 16:34:51
【问题描述】:

我正在尝试从我的项目中的本地文件夹动态渲染图像

对象结构是这样的

{
        id: 2,
        text: 'How would you describe your level of influence in management of the farm?',
        type: 'cardChoice',
        choices: [
          {
            id: 1,
            text: 'I am the primary decision maker',
            questionId: 'Hm?',
            value: 'I am the primary decision maker',
            image: '1.jpg',
          },
          {
            id: 2,
            text: 'I hent',
            questionId: 'Hrm?',
            value: 'I',
            image: '2.jpg',
          },
          {
            id: 3,
            text: 'I arm',
            questionId: '?',
            value: 'Irm',
            image: '3.jpg',
          },
        ],
      },

在我的组件中,我选择包含图像const baseUrl = '../../assets/images/CNA' 的文件夹 之后,在我返回时,我尝试渲染图像

<img src={`${baseUrl}'${questionChoice.image}'`} alt={questionChoice.text} />

页面呈现,但我的图片没有加载,而是显示我的alt

这是我的完整组件

const CardChoiceQuestions = ({ cardChoiceArray, currentAnswer, updateCurrent, submitAnswer }) => {
  const { id, value } = currentAnswer
  const baseUrl = '../../assets/images/CNA'
  return (
    <ButtonContainer>
      {cardChoiceArray.map(questionChoice => {
        return (
          <Button
            active={questionChoice.id === id}
            type="button"
            key={questionChoice.id}
            onClick={() => {
              const answer = { id: questionChoice.id, value: questionChoice.value }
              updateCurrent(answer)
              submitAnswer()
            }}
          >
            <p>{questionChoice.text}</p>
            <img src={`${baseUrl}${questionChoice.image}`} alt={questionChoice.text} />
          </Button>
        )
      })}
    </ButtonContainer>
  )
}

【问题讨论】:

    标签: reactjs image oop ecmascript-6


    【解决方案1】:

    我面前没有笔记本电脑,但我注意到了一些事情。您的基本网址后是否需要斜杠“/”?此外,字符串连接应在 $ 符号后的一组括号中完成。不确定这是否是问题尝试一些console.log(字符串路径)并验证它是否在您认为的位置。看起来路径可能是错误的。与构建动态 url 相比,使用条件渲染图像可能会更好,但无论哪种方式,它都应该在更改时呈现。

    【讨论】:

    • 好吧,我知道这已经有几天了,但是当我今天和我的一个朋友交谈时,我意识到了一些事情。 react 可能不会在 url 更改上呈现图像标签,只是因为它确实更改了 url 部分,所以图像可能不会总是重新呈现?正如旁注一样,更好的方法是使用 url 作为道具创建自己的图像组件。如果是这样,我认为它会在道具更改时呈现并获得新图片。因此,如果您仍然遇到问题,请尝试一下。
    【解决方案2】:
    <img src={`${baseUrl}/${questionChoice.image}`} alt={questionChoice.text} />
    

    这样使用

    【讨论】:

    • 不行,我觉得@Paul W 是对的,我的路径可能错了
    【解决方案3】:

    把这个留在这里以防有人遇到这个......

    <img src={require(`../../assets/images/CNA/${questionChoice.image}`)} alt={questionChoice.text} />
    

    不知道为什么我不能使用${baseUrl},但现在可以使用。

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 1970-01-01
      • 2019-09-20
      • 2021-03-22
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      相关资源
      最近更新 更多