我正在尝试将ReactJS与AngularJS一起使用,但它没有用完.有人可以指导我如何凝聚它们吗?或者请指出这里缺少什么?
我的index.html如下:
My Test
以下是我的reactExample.js的编写方式:
/** * @jsx React.DOM */ var testMy = React.createClass({ render: function(){ return (Hello
) } });
我的angularExample.js如下:
var myapp = angular.module('MyApp',[]); myapp.controller('Ctrl1',['$scope',function($scope){ $scope.clickMe = function(){ alert("Clicked!"); React.renderComponent(testMy, elem[0]); } }]);
它不显示任何内容(警报除外).我希望看到'Hello'打印在那里,但它会在控制台中抛出以下错误:
Error: Invariant Violation: prepareEnvironmentForDOM(...): Target container is not a DOM element
任何帮助将非常感激.
@Simon Smith已经提到了为什么错误出现在React.renderComponent
期望第二个参数,但你在控制器中玩DOM操作的方式是不合适的.在AngularJs
DOM中操作应该在directive
.让我们看看它是如何的
来自Facebook的React vs AngularJS:一篇仔细观察博客
React组件比Angular模板功能强大得多; 它们应该与Angular的指令进行比较.
这个博客的底部使用React和AngularJS一起,你可以看到如何angular
和react
可以一起玩.
来自反应网站
React组件实现了一个render()方法,该方法获取输入数据并返回要显示的内容.
在angularjs
组件中呈现directive
看看我整合的那个plunkerangularjs
和react
.
在react-example.js
我创造了virtual dom
元素
var Hello = React.createClass({ render: function() { return React.DOM.div({}, 'Hello ' + this.props.name); } });
和myMessage
指令渲染virtual dom
React.renderComponent(Hello({name: scope.myModel.message}), document.getElementById('example'));
其中virtual dom
的name
财产将与绑定scope.myModel.message
我会考虑通过指令进行集成,因为这通常是将非角度代码与角度集成的推荐方法.
这是一个例子:
angular.module('app').directive('greeting',[function(){ return { restrict:'AE', scope:{name:'@'}, link: function (scope, elem, attrs){ var GreetingSection = React.createClass({displayName: 'Greeting', render: function() { var message = "Good morning " + this.props.data.name + ", how are you?"; return React.createElement('div', {className: "greeting"},message); } }); React.renderComponent(GreetingSection({data:scope}), elem[0]); } }; }]);
更多信息:http: //www.syntaxsuccess.com/viewarticle/547bbd04fa0710440b45e41c
要在我的控制器中使用React,我这样做
myApp.controller(function($scope){ $scope.myComponent = {}; $scope.myComponent.setState({data: "something"}); });
在我的React组件中:
window.myComponent = React.createClass({ getInitialState: function(){ return { data:'' } }, componentWillMount: function(){ var scope = this.props.scope; scope.myComponent = this; }, render:func ..... });
我正在使用David Chang 的ngReact指令,它将$ scope作为属性传递给组件.所以现在你可以从你的控制器调用setState,强制react组件重新渲染:)
我在React-Sandbox中有一个更好的例子