利用react-to-web-component封装react控件

src/Greeting.tsx:

import React from "react";
import r2wc from "@r2wc/react-to-web-component";

type GreetingProps = {
	name: string;
};

const Greeting: React.FC<GreetingProps> = ({ name }) => {
	return <h2> Hello, {name} </h2>;
};

const GreetingWebComponent = r2wc(Greeting, {
	shadow: "open", // or "closed"
	props: { name: "string" },
});

customElements.define("greeting-wc", GreetingWebComponent);

declare global {
	namespace JSX {
		interface IntrinsicElements {
			"greeting-wc": { name: string };
		}
	}
}

src/App.tsx:

import "./Greeting.tsx";

export default () => {
	return (
		<div>
			<greeting-wc name="bill" />
		</div>
	);
};

index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
  </head>
  <body>
    <greeting-wc name="bill"></greeting-wc>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
posted @   卓能文  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示