1

私は React.js を使用してかなり複雑な Web アプリに取り組んでおり、アプリのユーザーがスクリプト タグ (Google Maps API、Analytics、等。)

React 初心者ですが、React はアプリ内のすべてのコンポーネントなどを取り込んで、1 つの JS ファイルにバンドルしていると思います。

コンポーネントを 1 つだけ JS ファイルにバンドルして、ユーザーがそのファイルをサイトに配置し、それをウィジェットとして使用できるようにすることはできますか?

ユーザーにウィジェットとして使用してもらいたいコンポーネントを reactify でトランスパイルしようとしましたが、うまく動作しません。

何かご意見は?

4

1 に答える 1

1

もちろん、依存関係として 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 を使用することです。

于 2016-11-07T15:24:28.977 に答える