javascript - 如何将网站插入 React 组件
问题描述
我有一个返回 html 的 API 响应,我想将响应插入到我的反应组件中
我已经试过了
<div dangerouslySetInnerHTML={{ __html: myApi.response }} />
然而,这会影响我的整个布局,因为它有自己的 CSS 和脚本。
解决方案
您可以使用 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
推荐阅读
- laravel - 删除记录并显示下一个而不重新加载整页?
- xpath - 从输入框中获取值不工作量角器
- java - 通过电子邮件字段保存或更新文档
- android - 如何使用来自 Retrofit POST 请求正文的响应来修改另一个 POST 请求的标头?
- ruby-on-rails - 如何检查旧提交是否与特定的新提交重叠
- java - 使用 linereader.readline() 跳过 csv 中的第一行但面临代码质量问题
- postman - Postman Prerequest Scripts 不断收到“ReferenceError: [variablename] is not defined”,但按照定义使用 pm.variables.set
- postgresql - 在 Postgres 中看不到 Keycloak 表
- node.js - 在Node.js中完成for循环后如何向客户端发送响应
- javascript - 使用 DataTables 时,自定义下拉搜索不允许我添加新项目