首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在React应用程序中包含带有钩子的Preact组件?

如何在React应用程序中包含带有钩子的Preact组件?
EN

Stack Overflow用户
提问于 2020-03-28 21:14:03
回答 1查看 2.5K关注 0票数 2

这听起来可能不寻常,但我试图导入Preact组件与Preact钩子在一个反应应用程序。不幸的是,这样做会引发一个Cannot read property '__H' of undefined。下面对此有更多的介绍。

假设,为了简单地回答这个问题,Preact组件驻留在一个包中,如下所示:

代码语言:javascript
复制
// 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应用程序中导入的:

代码语言:javascript
复制
...
import { PreactComponent } from 'mypackage';

const MyComponent = () => {
  return <PreactComponent />
};

这会抛出Unhandled Rejection (TypeError): Cannot read property '__H' of undefined

它肯定是 Preact挂钩相关的,因为删除Preact组件中的useRef会导致组件呈现良好。正如您在上面所看到的,钩子是在函数中定义的,应该是这样的。

是否有人试图使用带有钩子的Preact组件?你是怎么做的?

EN

回答 1

Stack Overflow用户

发布于 2020-04-02 06:41:27

这会抛出,因为renderer不知道Preact特定的内部组件。如果我们检查JSX的转置输出,就会得到以下结果:

代码语言:javascript
复制
// Won't work, PreactComponent is not a React component
React.createElement(PreactComponent, null)

解决这一问题的最简单方法是提供一个DOM节点,Preact可以在其中进行呈现。

代码语言:javascript
复制
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} />
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60907068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档