利用react-to-web-component封裝react控制元件

卓能文發表於2024-08-16

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);

src/App.tsx:

import "./Greeting.tsx"

export default () => {
  return <div>App Start here.</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>

相關文章