如何使用 React 创建可再分发的小部件

How to create a redistributable widget using React

我想使用 React 构建一个小部件,通过指向一个 js 文件并添加一个 javascript 片段,非水疗网站可以使用它。例如

<script src="somepath/mycomponent.min.js"></script>
<script>MyComponent.render('id-of-a-div')</script>

我已经使用 React 创建了一个组件并设置了 webpack。我大多数 spa 案例的顶级组件以

结尾
ReactDOM.render(<MyComponent/>, document.getElementById(id));

我的组件将无法执行此操作,因为它不知道要将自己呈现给哪个元素。

我应该如何以及在何处创建将组件附加到元素的函数?

您需要一个包含初始化和与父页面交互的方法的文件。

也许在 utilities.js

 export const utilities = {
   // Here you will initialize the widget and you could pass an argument 
  // with the id of the tag where you wanna inject the app 

   initWidget: ( elementId ) => {
    if( !elementId ){
     document.createElement( 'rootApp' ); 
     ReactDOM.render(<MyComponent/>, document.getElementById('rootApp'));
    }
    else {
     ReactDOM.render(<MyComponent/>, document.getElementById(id));
     }
   },
 } 

并且该实用程序将在 html 的标记中运行,以便在加载所有 js 后立即将其初始化:

<script type='text/javascript' src='/widget.js'></script>
<script>
 utilities.initWidget( 'myCustomId' );
</script>

也许这样的流程对您有用。