简体   繁体   English

反应来自 src 的动态图像不公开

[英]React dynamic image from src not public

I'm importing 3 images, depending on the value held in state I want to show one of the 3我正在导入 3 张图像,具体取决于 state 中的值 我想显示 3 张中的一张

import csv from '../../images/csv.svg';
import jpg from '../../images/jpg.svg';
import png from '../../images/png.svg';

in the state, I've got the file type在 state 中,我有文件类型

const [fileType, setFileType] = useState<'csv' | 'png' | 'png' | ''>('');

and in the body, I have the image在身体里,我有形象

<img src={fileType} />

I'm populating the state from the file name我从文件名填充 state

  useEffect(() => {
    if (file?.filePath) {
      const fileType = file?.filePath.slice(-3);
      setFileType(fileType);
    }
  }, [file?.filePath]);

The img src is always a string value not the file path, I suspect I'm storing the word 'jpg' instead of the reference to the jpg?? img src 始终是一个字符串值而不是文件路径,我怀疑我存储的是“jpg”一词而不是对 jpg 的引用?

Yes you are correct.是的,你是对的。 When you update your state to 'png', the image tag will render like this:当您将 state 更新为“png”时,图像标签将呈现如下:

<img src="png">

This is not a valid url to an image so it can't be displayed correctly.这不是图像的有效 url,因此无法正确显示。

Idk the exact type of an imported image in React, but this is a workaround that should work in your case: Idk React 中导入图像的确切类型,但这是一种适用于您的情况的解决方法:

import img1 from './test.svg';
import img2 from './test2.svg';

export const ExampleComponent = () => {
  const [image, setImage] = useState<typeof img1 | null>(null);

  // Now you can call setImage with whatever image you want

  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM