reactjs 我需要在React中拍摄图像

mum43rcc  于 2023-05-28  发布在  React
关注(0)|答案(2)|浏览(168)

如何将图像放入React-component?我的图像在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"}}/>

在我的postgres sql中,图像就像路径:../images/four_image.png

hi3rlvi2

hi3rlvi21#

<img src={require(avatar)}
alt={"Avatar"}
style={{marginLeft: "5%", width: "4vh"}}/>
hfyxw5xn

hfyxw5xn2#

如果图像文件在src/images中,我认为URL需要是images/first_image.png(您需要在开头丢弃'..'。如果所有头像图像都存储在此文件夹中,则最好仅将文件名存储在数据库中,并将img src设置为文件名+一个baseUrl:

<img src={baseUrl + avatarFilename}
    alt={"Avatar"}
    style={{marginLeft: "5%", width: "4vh"}}/>

何处

const baseUrl = 'images/'

相关问题