首页 > 解决方案 > 在 React 应用程序中,当图像 url 是对象的字符串属性时,图像无法显示

问题描述

当图像 url 是对象中的字符串属性时,我无法显示图像。例如:

import React, {Fragment, useState} from 'react';

const profile = (props) => {
  const [user, setUser] = useState(null);
  useEffect(() => {
    setUser({
      name: 'John',
      photo: './asset/images/user.png'
    })
  }, [])
  
  return (
    <Fragment>
      <img src={user.photo} alt="photo" />
      <p>{user.name}</p>  
    </Fragment>
  )
}

当然我可以通过导入像import img from './assets/images/user.png'. 但我需要知道如何在不导入图像的情况下显示图像。

有没有人解决问题?

标签: htmlreactjs

解决方案


您可以在这里看到一个示例:https ://codesandbox.io/s/relaxed-sinoussi-ikown?file=/src/App.js

主要问题是您试图将图像作为组件的相对路径访问。

但是,当您想做类似的事情时,您的组件可以位于应用程序中的任何位置。所以,这样做的方法是:

  • 将您的图像包含在public/
  • 使用绝对路径访问您的图像/public

推荐阅读