利用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 @ 2024-08-16 10:37  卓能文  阅读(121)  评论(0)    收藏  举报