简体   繁体   English

使用危险的SetInnerHtml时无法在反应nextjs中显示图像

[英]Unable to display image in react nextjs while using dangerouslySetInnerHtml

I was trying to create a simple WYSIWYG editor in nextjs.我试图在 nextjs 中创建一个简单的所见即所得编辑器。 Here I came across this problem, where I have to display the uploaded image to the screen.在这里我遇到了这个问题,我必须将上传的图像显示到屏幕上。 This could be easily done by creating a blob URL of the image and using the URL in the src of the image IF you are not using dangerouslySetInnerHtml.这可以通过创建图像的 blob URL 并在图像的 src 中使用 URL 来轻松完成,如果您没有使用危险的SetInnerHtml。 But while using it the link appears broken.但是在使用它时,链接似乎已损坏。 This was the result I was getting on the console.这就是我在控制台上得到的结果。

blob:http://localhost:3000/f28f5781-d2b0-4a20-9d56-10b9ae7f66e7/:1 GET blob:http://localhost:3000/f28f5781-d2b0-4a20-9d56-10b9ae7f66e7/ net::ERR_FILE_NOT_FOUND

Here is what I tried to do.这是我试图做的。 On image upload event, I trigger a function that sets the image URL using React.useState(), eg setImageUrl(objectUrl).在图像上传事件中,我触发了一个 function,它使用 React.useState() 设置图像 URL,例如 setImageUrl(objectUrl)。 here's the contentEditable div.这是 contentEditable div。 :

<div
            style={{ margin: "10px", border: "none", outline: "none" }}
            onBlur={handleBlur}
            contentEditable
            data-placeholder="Enter text here"
            onKeyUp={(e) => handleKeyUp(e)}
            dangerouslySetInnerHTML={{ __html: innerHtml }}
            onClick={(e) => handleContentEditableChange(e)}
          >

here is the innerHtml,Let me know if more info is needed.这是innerHtml,如果需要更多信息,请告诉我。 thanks谢谢

setInnerHtml(
        ${innerHtml}
        <p>${tempText}</p>
        <img src=${imageUrl}/>
      );
    /* here is what I am doing with the file, this code is triggered just after I upload the file */

    const objectUrl = URL.createObjectURL(file);
    setImageUrl(objectUrl); 
// the imageUrl is same as the one above in image src . P.S. i have made use of readAsDataUrl as well but failed to get the desired result

The browser is reading the img src as blob:http://localhost:3000/sth/ while it should be blob:http://localhost:3000/sth .浏览器将 img src 读取为blob:http://localhost:3000/sth/而它应该是blob:http://localhost:3000/sth To fix it, wrap imageUrl with quotes or remove the / or do both:要修复它,用引号包裹imageUrl或删除/或两者都做:

<img src="${imageUrl}" /> or <img src=${imageUrl} > or <img src="${imageUrl}" > <img src="${imageUrl}" /><img src=${imageUrl} ><img src="${imageUrl}" >

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

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