React:如何通过包含特殊字符的路径加载图像?

React: How to load an image by path that contains special characters?

我尝试通过包含 &@^ 等特殊字符的路径加载图像。

当我如下加载图像时,它不起作用。

<img src="file:///test/@#$%/0.png"/>

因此,我尝试使用 encodeURI(path)、encodeURIComponent(path),但都没有用。

我该怎么做?

您不能将它们呈现为字符串。如果你要使用它们,你必须写在数字代码或JS转义上。

您可以从 here

中找到他们的代码

如你所愿,

@ : &#64;
# : &#35;
$ : &#36;

您必须对路径中的每个级别进行编码(跳过 / 个字符):

const path = 'file:///test/@#$%/0.png'
const encodedPath = 'file://' + path.replace('file://', '').split('/').map((p) => encodeURIComponent(p)).join('/')
console.log(encodedPath)
// Output: file:///test/%40%23%24%25/0.png

将上面的输出用于您的 img 标签,它将被加载。