我如何在一个项目中结合Angular和React [英] How could I combine Angular and React in one project

查看:105
本文介绍了我如何在一个项目中结合Angular和React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面portal.html,该页面由Angular通过路线portal

I have a page portal.html which is rendered by Angular by the route portal

  state('portal', {
    url: '/',
    templateUrl: 'portal.html',
    controller: 'portalCtrl',
  })

但是,我想通过ReactJS实现一些UI组件交互.

However, some UI component interactions I want to implement with ReactJS.

我试图在主体末尾钩上react.js脚本(由webpack生成)

I tried to hook react.js script in the end of body (generated by webpack)

<script type="text/javascript" src="react_box/react_bundle.js"></script>

但是,我遇到了这个错误.

However, I got this error.

invariant.js:38Uncaught Invariant Violation: _registerComponent(...): Target container is not a DOM element.

我相信问题是由于当想要查找DOM时DOM还没有准备好.

I belive the problem is due to the DOM is not ready when react want to find the DOM.

在Angular准备好DOM之后,如何使反应开始工作?

How can I make the react start working after the DOM is ready by the Angular?

推荐答案

在将React组件包装在指令中之前,我已经将它们集成到了Angular应用中.这确保了React代码在正确的时间执行. (我认为您不能通过简单地将React内容作为script标签包含来确保Angular是就绪"的.)

I have integrated React components into an Angular app before by wrapping them in a directive. This ensures that the React code is executed at the right time. (I don't think you can ensure that Angular is "ready" by simply including the React stuff as a script tag).

指令看起来像这样:

var React = require('react');
var ReactComponent = require('./react-component.jsx');

function ReactDirective() {
   return {
       restrict: 'EA',
       scope: {
           data: '=data'
       },
       template: '<div></div>',
       link: function(scope, element) {
           var renderComponent = function(data) {
               React.render(React.createElement(ReactComponent, {data: data}), element[0]);
           };

           scope.$watch('data', function(newValues) {
               renderComponent(newValues);
           }, true);
        }
    };
}

module.exports = ReactDirective;

然后,您像往常一样包括该指令.如果您需要React代码与Angular代码进行交互,请将回调作为道具传递给React组件.

You then include the directive as normal. If you need the React code to interact with the Angular code, pass in callbacks as props to the React component.

这篇关于我如何在一个项目中结合Angular和React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆