将单个React组件转换成JS小部件

Transpile single React component to use as JS widget

本文关键字:JS 小部 转换 单个 React 组件      更新时间:2023-09-26

我正在使用React.js制作一个相当复杂的web应用程序,我想让应用程序的用户在他们的网站上使用其中一个组件作为API小部件以及脚本标签(认为谷歌地图API,分析等)

我是React的新手,但我认为React采用应用程序中的所有组件等,并将它们捆绑到一个JS文件中。

是否有可能只将一个组件捆绑到一个JS文件中,然后让用户将该文件放在他们的站点中,并将其用作小部件?

我已经尝试编译我想让用户使用的组件作为一个小部件与反应,但我似乎不能让它工作。

任何想法吗?

当然可以,但是他们仍然需要将React作为一个依赖项,否则你将不得不在你的小部件中包含React。

要使用React,你不需要使用transpilation,也就是说,你不需要reactify。为React构建小部件就像为jQuery构建小部件一样。

// Your widget root component
var SayHelloComponent = React.createClass({
  render() {
    // You use React.createElement API instead of JSX
    return React.createElement('span', null, "Hello " + this.props.name + "!");
  }
});
// This is a function so that it can be evaluated after document load
var getWidgetNodes = function () { 
  return document.querySelectorAll('[data-say-hello]'); 
};
function initializeWidget(node) {
  // get the widget properties from the node attributes
  var name = node.getAttribute('data-say-hello');
  // create an instance of the widget using the node attributes 
  // as properties
  var element = React.createElement(SayHelloComponent, { name: name });
  ReactDOM.render(element, node);
}
getWidgetNodes().forEach(initializeWidget);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!-- What it would look to include your widget in a page -->
<div data-say-hello="Guzart"></div>

您需要编译代码的唯一原因是使用JSX和ES6。