英文:
Edit a html getting from backend and render it in a react website
问题
我想在从后端获取的HTML中添加一些按钮(我想在每个<tr></tr>
中添加一个按钮)和元素。如何实现这个目标?
英文:
let htmlFromBackend = `Some backend HTML in table format`
return (
<div dangerouslySetInnerHTML={{ __html: htmlFromBackend}}></div>
)
I want to add some buttons(I want to add a button in every <tr></tr>
) and elements in the html getting from backend. How it can be acheived?
答案1
得分: 1
以下是翻译好的部分:
对于最简单的解决方案,您可以直接在HTML前面插入。例如:
return (
<div dangerouslySetInnerHTML={{ __html: `<button onclick="alert('Nice!')">Alert</button>${htmlFromBackend}`}}></div>
)
要在HTML的多个元素上插入按钮,您可以使用正则表达式或先解析它。我将为您展示一个示例,首先解析HTML并进行编辑。
function preprocessHTML(html){
const element=document.createElement('div');
element.innerHTML=html;
// 进行任何您喜欢的操作,例如:
for(const child of element.children){
const btn=document.createElement('button');
btn.innerText='Click Me!';
child.prepend(btn);
}
return element.innerHTML;
}
return (
<div dangerouslySetInnerHTML={{ __html: preprocessHTML(htmlFromBackend)}}></div>
)
如果您想要在React中插入,可以使用 ReactDOM.createPortal
将任何JSX元素渲染到任何HTML DOM 中。
英文:
For the simplest solution, you can prepend the HTML directly. For example:
return (
<div dangerouslySetInnerHTML={{ __html: `<button onclick="alert('Nice!')">Alert</button>${htmlFromBackend}`}}></div>
)
To prepend buttons on multiple elements of the HTML, you can either use RegExp or parse it first. I'll show you an example that parses the HTML first and edit it.
function preprocessHTML(html){
const element=document.createElement('div');
element.innerHTML=html;
// do any operations you like, for example:
for(const child of element.children){
const btn=document.createElement('button');
btn.innerText='Click Me!';
child.prepend(btn);
}
return element.innerHTML;
}
return (
<div dangerouslySetInnerHTML={{ __html: preprocessHTML(htmlFromBackend)}}></div>
)
If you want to prepend with React, you can use ReactDOM.createPortal
to render any JSX element to any HTMLDom.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论