编辑从后端获取的HTML,并在React网站中呈现它

huangapple go评论58阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月6日 19:21:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75360653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定