在 React 中封装 Custom Element 并同步 Props
解读
国内一线/二线公司面试时,这道题常被用来检验候选人对 React 与 Web Components 生态的融合深度。
面试官真正想听的是:
- 你是否理解 Custom Element 生命周期 与 React 生命周期 的差异;
- 能否在 不破坏 React 数据流 的前提下,把 React 组件“伪装”成 Custom Element,并保证 Props 单向同步(React → CE)与 事件反向同步(CE → React);
- 是否知道 React 19 官方支持的 custom-elements 编译开关,以及 16-18 时代的坑点(如
className变class、合成事件不冒泡等)。
回答时务必给出可运行的最小代码骨架,并主动说明如何在微前端、跨框架复用、低代码平台三个国内高频场景落地。
知识点
- CustomElementRegistry & 生命周期回调(constructor、connectedCallback、attributeChangedCallback、disconnectedCallback)
- React Ref 转发与 useImperativeHandle 暴露命令式 API
- React Props → CE Attributes/Properties 映射策略:
– 原始类型直接反射;
– 对象/数组用 JSON.stringify + 自定义 property 双写;
– 布尔值采用 hasAttribute 判定。 - React 事件系统与 CE 自定义事件的兼容:
– 使用 CustomEvent 透出 detail;
– 在 React 侧用 addEventListener 手动订阅(16-18),或直接使用 onMyEvent 形式(19 自动绑定)。 - Shadow DOM 样式隔离与 CSS Custom Properties 穿透方案,避免国内常见的“组件库换肤”需求翻车。
- 性能陷阱:attributeChangedCallback 高频触发 → 防抖 + shouldUpdate;
- TypeScript 类型声明:声明模块
*.d.ts使JSX.IntrinsicElements认识自定义标签,否则国内 CI 会报错。
答案
// 用 React 19 语法(兼容 16+ 只需把事件绑定换成 useEffect)
import React, { forwardRef, useRef, useLayoutEffect, useImperativeHandle } from 'react';
type Props = {
title: string;
active?: boolean;
onToggle?: (open: boolean) => void;
};
// 1. 定义 Custom Element,内部渲染 React 树
class ReactBadge extends HTMLElement {
static get observedAttributes() {
return ['title', 'active'];
}
mountPoint!: HTMLDivElement;
reactRoot: any;
connectedCallback() {
this.mountPoint = document.createElement('div');
this.attachShadow({ mode: 'open' }).appendChild(this.mountPoint);
this.upgradeProperty('active'); // 把可能通过 property 设置的值同步到 attribute
this.renderReact();
}
attributeChangedCallback() {
this.renderReact();
}
disconnectedCallback() {
// React 18 createRoot 卸载
this.reactRoot?.unmount();
}
// 暴露给原生端的命令式 API
toggle() {
const current = this.hasAttribute('active');
this.toggleAttribute('active', !current);
}
private upgradeProperty(prop: string) {
if (this.hasOwnProperty(prop)) {
const value = (this as any)[prop];
delete (this as any)[prop];
if (prop === 'active') this.toggleAttribute('active', Boolean(value));
else this.setAttribute(prop, String(value));
}
}
private renderReact() {
// 懒加载 createRoot,避免重复创建
if (!this.reactRoot) {
const ReactDOM = require('react-dom/client');
this.reactRoot = ReactDOM.createRoot(this.mountPoint);
}
const title = this.getAttribute('title') || '';
const active = this.hasAttribute('active');
this.reactRoot.render(
<BadgeReact
title={title}
active={active}
onToggle={(open) => {
// 反向同步:React 事件 -> CE 自定义事件
this.dispatchEvent(
new CustomEvent('toggle', { detail: open, bubbles: true })
);
}}
/>
);
}
}
// 2. 真正的 React 实现,无 CE 逻辑,方便单元测试
const BadgeReact: React.FC<{
title: string;
active: boolean;
onToggle: (open: boolean) => void;
}> = ({ title, active, onToggle }) => (
<span
className={`badge ${active ? 'active' : ''}`}
onClick={() => onToggle(!active)}
>
{title}
</span>
);
// 3. 注册 Custom Element
customElements.define('react-badge', ReactBadge);
// 4. React 侧再包一层,方便像普通 React 组件一样使用
export const Badge = forwardRef<ReactBadge, Props>((props, ref) => {
const ceRef = useRef<ReactBadge>(null);
useLayoutEffect(() => {
const node = ceRef.current;
if (!node) return;
// Props 同步 -> Attribute/Property
node.setAttribute('title', props.title);
props.active ? node.setAttribute('active', '') : node.removeAttribute('active');
// 事件监听
const handler = (e: Event) => props.onToggle?.((e as CustomEvent).detail);
node.addEventListener('toggle', handler);
return () => node.removeEventListener('toggle', handler);
}, [props.title, props.active, props.onToggle]);
useImperativeHandle(ref, () => ceRef.current!, []);
return <react-badge ref={ceRef} />;
});
使用示例
function App() {
const badgeRef = useRef<ReactBadge>(null);
return (
<>
<Badge
ref={badgeRef}
title="新消息"
active
onToggle={(open) => console.log('开关状态', open)}
/>
<button onClick={() => badgeRef.current?.toggle()}>原生调用</button>
</>
);
}
关键点总结
- Props 同步:React 侧用
useLayoutEffect把变化映射到 CE 的 attribute/property; - 事件反向:CE 内部 dispatch
CustomEvent,React 侧用addEventListener订阅; - 命令式 API:通过
useImperativeHandle把 CE 实例直接抛给父组件,满足国内低代码平台“拖拽即调用”需求; - Shadow DOM:示例已开启,避免样式污染主应用,但用 CSS 变量穿透换肤;
- 兼容性:React 16-18 需把
createRoot换成ReactDOM.render,并额外引入@webcomponents/custom-elements垫片以支持 IE11(国内政务项目仍有要求)。
拓展思考
- 微前端场景:当主应用是 Vue3、子应用是 React 时,把子应用整个包成 Custom Element,用 qiankun 的 customElement 模式接入,可避免全局变量冲突;此时需把 React 使用的全局样式抽成 CSS-in-JS 动态插入 Shadow DOM,否则主应用样式会失效。
- 表单校验:若 CE 内部是复杂表单,把校验方法挂到 CE 实例上,父框架(如 Ant Design Vue)可通过
ref.value.validate()直接调用,实现“黑盒复用”。 - 性能优化:Props 变化频繁时,在 CE 侧加
shouldComponentUpdate类似逻辑,对比新旧 JSON 字符串,减少 React 重渲染;同时用 MutationObserver 监听 attribute 变化,批量更新。 - SSR 兼容:国内 SEO 要求强,Next.js 服务端渲染时 Custom Element 标签会被原样输出,需在客户端
hydrate阶段延迟创建 Shadow Root,否则会出现hydration mismatch;官方方案是 dynamic import + ssr: false,但更好的做法是 用@lit-labs/ssr把 CE 也服务端渲染成字符串,实现“同构”。 - 安全合规:银行/政务项目要求 禁止内联脚本,Shadow DOM 内的
script标签会被 CSP 拦截,需把逻辑全部编译到主 bundle,CE 只负责渲染,避免运行时eval。