2016-11-07 29 views
0

我正在使用React.js處理相當複雜的Web應用程序,並且我希望允許應用程序的用戶在其站點上使用其中一個組件作爲API小部件與腳本標記(認爲谷歌地圖API,分析等)將單個React組件用作JS小部件

我是新來的React,但我覺得React需要應用程序中的所有組件等,並將它們捆綁到一個單一的JS文件。

是否有可能只將一個組件綁定到一個JS文件中,然後讓用戶將該文件放在他們的站點中,並將其用作一個小部件?

我試着將我希望用戶用作小部件的組件轉換爲組件reactify,但似乎無法使其運行。

有什麼想法?

回答

1

當然,他們仍然需要將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>

你需要transpile你的代碼是使用JSX和ES6的唯一原因。

+0

我的組件同時使用JSX和ES6。哈哈。那麼,你認爲使用JSX和ES6的組件轉換將作爲一個小部件工作?我可以直接在窗口小部件中放置React,以便用戶不必在他或她的網站上添加其他js依賴項? – tsteve

+0

從ES6和JSX轉換將輸出類似於答案中代碼片段的內容。是的,你可以在你的小部件中包含React和ReactDOM,如果它們尚未包含在頁面中,最好是加載它們。這裏重要的一點是,你明白獲得一個反應小部件的最小工作是什麼。在你的問題中,你提到你無法使其工作,沒有代碼和配置很難幫助你識別問題。 – guzart