簡體   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