如何在两个窗口之间使用钩子共享组件?

时间:2020-06-22 11:57:16

标签: reactjs typescript react-hooks

我正在尝试在两个窗口之间共享组件。 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'));

1 个答案:

答案 0 :(得分:0)

自我解决:
通过将React用作道具并在组件内部使用它来解决。

index.ts

import React, { FC, useState } from 'react';
import ReactDOM from 'react-dom';

const ComponentWithHook: FC<{ React: typeof React }> = ({ React }) => {
  const [value] = React.useState('xxxx');
  return <>{value}</>;
};

(window as any).getComponent = () => ComponentWithHook;

ReactDOM.render(<iframe src="iframe.html" />, document.getElementById('root'));

iframe.ts

import React, { FC } from 'react';
import ReactDOM from 'react-dom';

const Dummy: FC = () => {
  const ComponentWithHook = (top as any).getComponent();
  return <ComponentWithHook React={React} />;
};

ReactDOM.render(<Dummy />, document.getElementById('root'));
相关问题