繁体   English   中英

转换单个React组件以用作JS小部件

[英]Transpile single React component to use as JS widget

我正在使用React.js开发一个相当复杂的网络应用程序,我希望允许该应用程序的用户使用其组件之一作为其网站上的API小部件以及脚本标签(例如Google Maps API,Analytics,等等。)

我是React的新手,但我认为React将应用程序中的所有组件等都打包到一个JS文件中。

是否可以仅将一个组件捆绑到一个JS文件中,然后让用户将该文件放在其站点中,然后将其用作小部件?

我尝试使用reactify来编译我希望用户用作窗口小部件的组件 ,但是我似乎无法使其正常工作。

有什么想法吗?

绝对,但是它们仍然需要将React作为依赖项包括进来,否则您将不得不在其小部件中。

要使用React,您不需要使用转译,即您不需要react。 为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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM