英文:
I need to take an image in React
问题
如何将图像嵌入React组件?
我的图像位于srs/images
中。
我尝试通过以下方式获取它:
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get("http://127.0.0.1:5000/api/user", {
headers: {
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
});
const {
firstName,
lastName,
avatar
} = response.data;
setFirstName(firstName);
setLastName(lastName);
setAvatar(avatar);
} catch (error) {
console.error("Error fetching user data:", error);
}
};
fetchData();
}, []);
我的头像看起来像../images/first_image.png
,然后我无法在以下位置查看它:
<img src={avatar}
alt={"Avatar"}
style={{marginLeft: "5%", width: "4vh"}}/>
在我的PostgreSQL中,图像的路径如下:
../images/four_image.png
英文:
How can i take an images into React-component?
My image is in srs/images.
I try to take it by:
useEffect(() => {
const fetchData = async() => {
try {
const response = await axios.get("http://127.0.0.1:5000/api/user", {
headers: {
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
});
const {
firstName,
lastName,
avatar
} = response.data;
setFirstName(firstName);
setLastName(lastName);
setAvatar(avatar);
} catch (error) {
console.error("Error fetching user data:", error);
}
};
fetchData();
}, []);
my avatar looks like ../images/first_image.png
and than i can't view it in
<img src={avatar}
alt={"Avatar"}
style={{marginLeft: "5%", width: "4vh"}}/>
in my postgres sql the image is like the path:
../images/four_image.png
答案1
得分: 1
<img src={require(avatar)} alt={"头像"} style={{marginLeft: "5%", width: "4vh"}}/>
英文:
<img src={require(avatar)}
alt={"Avatar"}
style={{marginLeft: "5%", width: "4vh"}}/>
答案2
得分: -1
如果图像文件位于src/images文件夹中,我认为URL应该是images/first_image.png(需要删除开头的'..')。如果所有头像图像都存储在此文件夹中,最好只在数据库中存储文件名,并使img src为文件名+baseUrl:
<img src={baseUrl + avatarFilename}
alt={"Avatar"}
style={{marginLeft: "5%", width: "4vh"}}/>
其中
const baseUrl = 'images/';
英文:
If the image file is in src/images I think the url needs to be images/first_image.png (you need to ditch the '..' at the beginning. If all avatar images are stored in this folder, it might be best to store just the filename in the database and have the img src be the filename + a baseUrl:
<img src={baseUrl + avatarFilename}
alt={"Avatar"}
style={{marginLeft: "5%", width: "4vh"}}/>
where
const baseUrl = 'images/'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论