使用 Web Components 在 React App 中实现 Solid 组件
我想在 React 应用中使用 Solid 元素。最终,一切进展顺利,这让我感到惊喜。
这是一份重点突出重要步骤的快速指南。
优势
- 即使没有框架,您也可以在任何地方使用相同的组件。
- 输出尺寸非常小并且不包含很大的运行时间。
- Solid 带来的所有好东西。
范围
在 Solid 中使用 React 组件,或者在这个自定义组件中使用子 React 组件都是一些难题,我就不提了。
资源
solid-element 库:
https://github.com/solidjs/solid/tree/main/packages/solid-element
在深入研究之前先了解一些内容会更容易:
https://developer.mozilla.org/en-US/docs/Web/Web_Components
最佳实践:
https://developers.google.com/web/fundamentals/web-components/best-practices
“旨在仅接受丰富的数据(对象,数组)作为属性。”
步骤
1-从模板开始npx degit solidjs/templates/ts my-app
2-添加依赖项pnpm i solid-element
3-改变vite.config.ts
import { defineConfig } from "vite";
import solidPlugin from "vite-plugin-solid";
const path = require('path')
export default defineConfig({
plugins: [solidPlugin()],
build: {
target: "esnext",
polyfillDynamicImport: false,
lib: {
entry: path.resolve(__dirname, 'src/MyComponent.tsx'),
name: 'MyLib'
},
},
});
4-创建组件MyComponent.tsx
import { onMount, createSignal, createEffect, For } from "solid-js";
import { createStore } from "solid-js/store";
import { customElement } from "solid-element";
const [getData, setData] = createSignal("");
interface Options {
option1: string;
option2: number;
}
customElement(
"my-custom-component",
{
data: { getData, setData, getOtherData: null },
},
(
props: {
data: {
// flowdata: string;
getData: () => string;
setData: (v: string) => string;
getOtherData: (options: Options) => Promise<string>;
};
},
{ element }
) => {
let internal_el;
props.data.getOtherData = async (
options: Options = { option1: "default", option2: 1 }
): Promise<string> => {
let promise = new Promise<string>((resolve, reject) => {
//do something
resolve("data");
});
return promise;
};
const [state, setState] = createStore({});
onMount(() => {
// code
});
createEffect(() => {
// getData() will be reactive here
// you can use the passed data to do calculation / render elements
getData();
});
return <div ref={internal_el}></div>;
}
);
5-更改package.json
名称字段:"name": "my-custom-component"
6-运行npm run build
现在你可以在目录下看到结果了dist
。就这些。你可以复制my-custom-component.es.js
到你的 React 项目,或者使用一些多仓库设置。
7- 在 React 方面,您可以使用方法与自定义组件交换数据。
import "../vendor/my-custom-component.es.js";
function Component1(props) {
const customControlRef = useRef<any>(null);
useEffect(() => {
customControlRef.current.data.setData(specialData);
}, []);
const getData2 = async (ev) => {
await customControlRef.current.data.getOtherData();
};
return (
<div>
<my-custom-component ref={customControlRef}></my-custom-component>
<button className="button" onClick={getData2}>
Get some data from Custom Component
</button>
</div>
);
}
8- 奖励:如果您使用 Typescript,请在 React 中的组件代码之前添加此内容。
declare global {
namespace JSX {
interface IntrinsicElements {
"my-custom-component": React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
}
}
}