html - 在 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'
. 但我需要知道如何在不导入图像的情况下显示图像。
有没有人解决问题?
解决方案
您可以在这里看到一个示例:https ://codesandbox.io/s/relaxed-sinoussi-ikown?file=/src/App.js
主要问题是您试图将图像作为组件的相对路径访问。
但是,当您想做类似的事情时,您的组件可以位于应用程序中的任何位置。所以,这样做的方法是:
- 将您的图像包含在
public/
- 使用绝对路径访问您的图像
/public
推荐阅读
- oracle - 使用 GCP Dataflow 束作业和 python sdk 从 Oracle 数据库中提取数据
- c# - 升级 NuGet 包 (.Net Framework) 时,并非所有程序集引用都在更新
- r - 如何管理 .Rmd 文件中的块,例如突出显示代码块并显示块管理片段?
- python - YAML 管道无法将带有特殊字符的输入参数解析为 Python 任务
- java - Gson 和泛型映射
- unity3d - 如何统一替换“.hasChanged”
- javascript - 将文本添加到画布中的输入元素
- python - 有没有办法告诉 `spack env activate` 只通过文件系统带来 python 包?
- javascript - 用一定数量的单词包裹 javascript 文本
- seo - 如何在 Firebase 中为特定 URL 提供 410 状态代码?