在react dangerouslySetInnerHTML中将json显示为html



我正试图在react的弹出窗口中显示axios调用的html响应。这是我正在做的。我首先在我的组件中打电话:

useEffect(() => {
const previewTemplate = getPreviewTemplate(props.customFields);
previewTemplate.then(htmlResponse => {
setHtmlTemplate(htmlResponse.data);
});
}, [props.customFields])

方法是

const getPreviewTemplate = async (template) => {
let result;
try {
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
result = await axios.post('http://localhost:5000/template-preview',
{html: template.previewHtml}, headers
)
} catch (error) {
if (error.response) {
return error.response
} else if(error.request) {
return error.request
}
}
return result;
}

这将运行并返回一个html布局。然后,当我点击一个按钮时,我会尝试让它弹出。(为简洁起见,已删除所有onChange等(

<Popup
>
<div dangerouslySetInnerHTML={{__html: htmlTemplate}} />
</Popup>

HTML代码出现在弹出窗口中,并显示错误:

Error: ENAMETOOLONG: name too long, open '/Volumes/OGX/Code/itsyoo-build/server/views/layouts/
<style media="screen,print">
#g-handyman---patch-shape-box ,
#g-handyman---patch-shape-box .g-artboard {
margin:0 auto;
}
#g-handyman---patch-shape-box p {
margin:0;
}
.. etc

我做错了什么?我期望的行为是代码以html格式显示,而不是像显示的可见字符串那样。

虽然我希望您的代码能正常工作,但它肯定不是"React";做事的方式。React团队肯定会把你推向动态import,所以当弹出窗口打开时,该组件的JavaScript捆绑包会被提取和渲染,所有这些都在Reactland中。

但我相信你问了这个问题,因为动态导入超出了你的项目的范围。在我看来,如果您看到ENAMETOOLONG,那么您就遇到了服务器错误。请检查请求是否实际返回了200,并且您的服务器是否没有任何问题。

最新更新