React Web Component在Angular中加载失败:adoptedCallback查询报错
React转Web Component在Angular中引入报错的解决方案
我用React编写了一个简单的Web Component,代码如下:
import React from "react"; import ReactDOM from "react-dom/client"; import reactToWebComponent from 'react-to-webcomponent'; function Test() { return ( <h1> Hello </h1> ) } const webcomponent = reactToWebComponent(Test, React, ReactDOM ); customElements.define("hello-react", webcomponent);
单独用http-server运行正常,但在Angular应用中引入时,触发以下错误:
react-to-webcomponent.es.js:44 Uncaught TypeError: Cannot use 'in' operator to search for 'adoptedCallback' in undefined at Object.getOwnPropertyDescriptor (react-to-webcomponent.es.js:44) at Proxy.hasOwnProperty (<anonymous>) at zone-evergreen.js:2171 at Array.forEach (<anonymous>) at CustomElementRegistry.target.<computed> [as define] (zone-evergreen.js:2168) at index.js:8 at index.js:8 at index.js:8
方案1:调整ReactDOM导入方式
react-to-webcomponent对React 18的react-dom/client导入存在兼容问题,需改用传统的ReactDOM导入:
修改React代码中的导入语句:
// 替换原react-dom/client导入 import ReactDOM from "react-dom";
重新构建Web Component后,再引入到Angular中测试。
方案2:禁用Zone.js对自定义元素的包装
若方案1无效,问题根源是Angular的Zone.js对customElements.define做了代理包装,导致react-to-webcomponent无法正确访问自定义元素回调方法。需在Angular项目中禁用该行为:
- 打开
src/polyfills.ts文件 - 在文件顶部添加代码:
(window as any).__Zone_disable_customElements = true;
- 重启Angular开发服务
内容的提问来源于stack exchange,提问作者Ajinath Jedhe
相关产品推荐
相关产品推荐

