Вопрос

I have been using AngularJS heavily for the last 6 months and fully into the cult for about a year now. I have just come across ReactJS and love its ideas.

ReactJS claims to be the V in MVC architecture style, how can this work together with an AngularJS application to become the 'V'?

Это было полезно?

Решение

Angular is really great at some things, like forms and routing. React is really great at some things as well, like creating interactive widgets and generally displaying information in any way you could want, without having confusing code (this can be a bit crazy in angular at times).

If you want to use them together, you're best off having React only display information, but not really get information out of the component. I've had some headaches with digest loops when trying to use React components in angular because they have different "flows". It works well with simple events like clicks, but it's more troublesome with two way bindings for inputs.

The general practice seems to be wrapping a react component in a directive. This includes the basic requirements for a good component; initialization, updating, and cleanup.

angular.module('app.common.my-component', [])
.directive('myComponent', function() {
  return {
    restrict: 'E',
    scope: {
      'onClick': '&',
      'name': '@'
    },
    link: function (scope, element, attrs, ctrl) {
      // loading some things from a browserify bundle
      var MyReactComponent = require("web-common").MyReactComponent;
      var React = require('react');

      var angularElement = angular.element("<div></div>");
      element.append(angularElement);
      var reactElement = angularElement[0];
      angularElement = null;

      var render = function(){
          var component = React.createElement(MyReactComponent, {
              name: scope.name,
              onClick: function(e){
                  scope.onClick(e);
              }
          });
          React.render(component, reactElement);
      };

      scope.$watch("name", function(name){
          render();
      });

      scope.$on("$destroy", function(){
        React.unmountComponentAtNode(reactElement);
        reactElement = null;
      });

      render();
    }
  }
});

Feel free to edit this if you have improvements. It can always be reverted :-)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top