【发布时间】:2020-06-22 11:57:16
【问题描述】:
我正在尝试在两个窗口之间共享组件。 index.html 有一个 iframe,其 src 是 iframe.html。我希望iframe.html 渲染index.html 中定义的组件。这很好用,只要组件不使用任何钩子。如果使用了钩子,就会出现Invalid hook call 错误。这是解释的代码。你有什么解决方法吗?
index.html
<body><div id="root"></div><script src="index.js"></script></body>
index.ts
import React, { FC, useState } from 'react';
import ReactDOM from 'react-dom';
const ComponentWithHook: FC = () => {
const [value] = useState('xxxx');
return <>{value}</>;
};
(window as any).getComponent = () => ComponentWithHook;
ReactDOM.render(<iframe src="iframe.html" />, document.getElementById('root'));
iframe.html
<body><div id="root"></div><script src="iframe.js"></script></body>
iframe.ts
import React, { FC } from 'react';
import ReactDOM from 'react-dom';
const Dummy: FC = () => {
const ComponentWithHook = (top as any).getComponent();
return <ComponentWithHook />;
};
ReactDOM.render(<Dummy />, document.getElementById('root'));
【问题讨论】:
-
以这种方式共享组件让我感觉很奇怪。我更愿意为该组件创建另一个脚本,并且 index.ts 和 iframe.ts 都将导入并使用它。
-
是的,一般情况下我是这么认为的。但是这次就需要用这种方式共享组件了。
标签: reactjs typescript react-hooks