我有一个使用 Vite 创建的 React 应用程序,它有 4 个组件,它们是显示一些信息的材料 ui 表格。我希望其中一个成为一个小部件,这样就可以通过将其 URL 放入 Iframe 中来在当前应用程序和其他应用程序中使用它。
我在网上看到过有关将整个应用程序转换为小部件的文章,但就我而言,我只想将一个组件转换为小部件。
创建一个要用作小部件的 React 组件。确保该组件是独立的并且不依赖于主应用程序的全局状态。 示例:
import React from 'react';
import { YourTableComponent } from './YourTableComponent';
const WidgetComponent = () => {
return (
<div>
<h2>Widget Title</h2>
<YourTableComponent />
{/* Add other necessary components */}
</div>
);
};
export default WidgetComponent;
之后,您需要创建一个页面作为小部件的入口点。
import WidgetComponent from '../components/WidgetComponent';
const WidgetPage = () => {
return <WidgetComponent />;
};
export default WidgetPage;
然后您可以将 iframe 放置在您想要的位置
<iframe
title="Your Widget"
src="http://localhost:3000/widget"
...
></iframe>
希望能有所帮助。 我尝试了 next.js 项目,看起来不错。
您也可以在这里检查 vite.config 文件:
export default {
build: {
lib: {
entry: 'src/WidgetComponent.js',
name: 'WidgetComponent',
},
},
};