【问题标题】:How to share components with hooks between two windows?如何在两个窗口之间共享带有钩子的组件?
【发布时间】: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


【解决方案1】:

自我解决:
它通过将 React 作为 prop 传递并在组件中使用它来解决。

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'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-04
    • 2019-09-19
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多