简体   繁体   English

如何在危险的SetInnerHTML 内容中呈现反应组件?

[英]How to Render a react component inside a dangerouslySetInnerHTML content?

HTML content getting from server and rendering on UI using dangerouslySetInnerHTML inside a particular element. HTML 内容从服务器获取并在特定元素内使用dangerouslySetInnerHTML SetInnerHTML 在 UI 上呈现。

My question is to render React component inside the dangerouslySetInnerHTML content using some identifiers like id .我的问题是使用一些标识符(如iddangerouslySetInnerHTML SetInnerHTML 内容中呈现 React 组件。

While possible, this is sort of the wrong approach.虽然可能,但这是一种错误的方法。 dangerouslySetInnerHtml expects a string, so you would have to render the React component to a string and insert it into the HTML string before setting it... or use a hook to manipulate the DOM after it's been rendered, but that's against React best practices; dangerouslySetInnerHtml需要一个字符串,因此您必须将 React 组件呈现为一个字符串,然后在设置之前将其插入到 HTML 字符串中……或者在呈现后使用钩子来操作 DOM,但这违反了 React 最佳实践; you should let React manage the DOM and its changes.你应该让 React 管理 DOM 及其更改。

Since you mentioned getting HTML back from the server, I would suggest making a change there.由于您提到从服务器取回 HTML,我建议在那里进行更改。 Instead of returning HTML from the server, return JSON data.不是从服务器返回 HTML,而是返回 JSON 数据。 On the client side, you can take the JSON and populate the React components you need to render, without using dangerouslySetInnerHtml at all.在客户端,您可以使用 JSON 并填充您需要渲染的 React 组件,而根本不使用dangerouslySetInnerHtml的SetInnerHtml。

Returning HTML in response to AJAX calls was common in the early days of AJAX, but it is now standard practice to return "raw" data for exactly these reasons.在 AJAX 的早期,返回 HTML 以响应 AJAX 调用是很常见的,但现在正是出于这些原因返回“原始”数据的标准做法。 If some of your HTML is defined client side, and some server side, it will be very challenging to manage DOM scripting & interactivity on the client.如果您的某些 HTML 是在客户端定义的,而某些是在服务器端定义的,那么在客户端管理 DOM 脚本和交互性将非常具有挑战性。

dangerouslySetInnerHtml cannot render react components, because it does not accepts components.危险的SetInnerHtml 不能渲染反应组件,因为它不接受组件。 It accepts only a html string.它只接受一个 html 字符串。

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

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