这听起来可能不寻常,但我试图导入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会导致组件呈现良好。正如您在上面所看到的,钩子是在函数中定义的,应该是这样的。
是否有人试图使用带有钩子的Preact组件?你是怎么做的?
发布于 2020-04-02 06:41:27
这会抛出,因为renderer不知道Preact特定的内部组件。如果我们检查JSX的转置输出,就会得到以下结果:
// Won't work, PreactComponent is not a React component
React.createElement(PreactComponent, null)解决这一问题的最简单方法是提供一个DOM节点,Preact可以在其中进行呈现。
import React, { useRef, useEffect } from "react";
import { render, h } from "preact";
import { PreactComponent } from "./whatever";
function ReactPreactBridge() {
// Get the raw DOM node to render into
const ref = useRef(null)
useEffect(() => {
if (ref.current) {
// Can't use two different JSX constructors in
// the same file, so we're writing the JSX output
// manually. (h is the same as createElement)
render(h(PreactComponent, null), ref.current)
}
return () => {
// Clear Preact rendered tree when the parent React
// component unmounts
render(null, ref.current);
}
}, [ref.current]);
return <div ref={ref} />
}https://stackoverflow.com/questions/60907068
复制相似问题