首页 > 解决方案 > 如何将网站插入 React 组件

问题描述

我有一个返回 html 的 API 响应,我想将响应插入到我的反应组件中

我已经试过了

<div dangerouslySetInnerHTML={{ __html: myApi.response }} />

然而,这会影响我的整个布局,因为它有自己的 CSS 和脚本。

标签: javascriptreactjs

解决方案


您可以使用 iframe 并设置其 html,然后更改 iframe 样式

  const iframeRef = React.useRef(null)

  React.useEffect(() => {
    if (iframeRef && iframeRef.current) {
      const apiResponse = `
        <html>
        <body style="width: 100vw; height: 100vh; background: lime">
          Hello
        </body>
        </html>
      `;
      const doc = iframeRef.current.contentWindow.document;
      doc.open();
      doc.write(apiResponse);
      doc.close();
    }
  }, [])

  return (
    <div className="App">
      <iframe ref={iframeRef} />
    </div>
  );

看看https://codesandbox.io/s/focused-wood-jpf79?file=/src/App.js


推荐阅读