【发布时间】:2020-03-28 21:14:03
【问题描述】:
这听起来可能不寻常,但我正在尝试在 React 应用程序中导入带有 Preact 钩子的 Preact 组件。不幸的是,这样做会引发Cannot read property '__H' of undefined。更多内容如下。
假设,为了简单起见,Preact 组件位于这样的包中:
// src/components/index.js
import { h } from 'preact';
import { useRef } from 'preact/hooks';
const PreactComponent = () => {
const ref = useRef(null);
return <div ref={ref}>Hello World</div>;
};
// package.json
{
"name: "mypackage",
"main": "dist/index.js", // Output by Webpack, with src/components/index.js as entrypoint.
...
}
标准的东西。它被导入到 React 应用程序中:
...
import { PreactComponent } from 'mypackage';
const MyComponent = () => {
return <PreactComponent />
};
这会抛出Unhandled Rejection (TypeError): Cannot read property '__H' of undefined。
肯定与 Preact 钩子相关,因为在 Preact 组件中删除 useRef 会导致组件渲染正常。正如您将在上面看到的,钩子是在函数内部定义的,应该是这样。
有没有人尝试在 React 中使用带有钩子的 Preact 组件?你是怎么做的?
【问题讨论】: