gpt4 book ai didi

angularjs - 将 ReactJS 与 AngularJS 结合使用

转载 作者:行者123 更新时间:2023-12-03 13:02:35 25 4
gpt4 key购买 nike

我正在尝试将 ReactJS 与 AngularJS 一起使用,但没有成功。谁能指导我如何将它们粘合在一起?或者请指出这里缺少什么?

我的index.html如下:

<!DOCTYPE html>
<html data-ng-app="MyApp">
<head>
<title>My Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body data-ng-controller="Ctrl1">
<div id="myDiv">
<button id="btn1" data-ng-click="clickMe()">Click Me</button>
</div>
<script src="http://fb.me/react-0.8.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.8.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
<script type="text/jsx" src="reactExample.js"></script>
<script src="angularExample.js"></script>
</body>
</html>

这是我的reactExample.js的编写方式:

/**
* @jsx React.DOM
*/
var testMy = React.createClass({
render: function(){
return ( <p>Hello</p>)
}
});

我的 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 需要第二个参数,但在 Controller 内进行 DOM 操作的方式不合适。在 AngularJs 中,DOM 操作应该在指令中。让我们看看它会怎样

来自Facebook's React vs AngularJS: A Closer Look博客

React components are far more powerful than Angular templates; they should be compared with Angular's directives instead.

在本博客的底部一起使用 React 和 AngularJS 部分,您可以看到 Angularreact 如何一起使用。

来自react网站

React components implement a render() method that takes input data and returns what to display.

angularjs中,组件由指令渲染

查看此plunker我在其中集成了 angularjsreact

react-example.js中我创建了virtual dom元素

var Hello = React.createClass({
render: function() {
return React.DOM.div({}, 'Hello ' + this.props.name);
}
});

myMessage指令渲染虚拟dom

React.renderComponent(Hello({name: scope.myModel.message}), document.getElementById('example'));

其中virtual domname属性将与scope.myModel.message绑定(bind)

关于angularjs - 将 ReactJS 与 AngularJS 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20947191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com