我试图用React渲染来实现替换Angular ng-repeat的“快速重复”模式.我可以渲染一个基本表,但该表需要支持自定义Angular指令.我可以在React(作为属性)中获取自定义指令,但它们不起作用.基于谷歌先生,这应该是可能的,但在我看来,或许我需要在React渲染的
HTML上进行$compile,其中包含我的自定义指令……或者不是.
这是我的精简测试代码. ‘react-test’指令似乎正确地呈现了ReactClass组件,其中包含一个’ng-monkey’属性,该属性本身就是一个Angular自定义指令.猴子似乎不起作用.有什么建议?
<!DOCTYPE html> <html> <head> <Meta charset="utf-8" /> <title>Angular React Test</title> <Meta http-equiv="X-UA-Compatible" content="IE=edge"> <Meta content="width=device-width,initial-scale=1.0" name="viewport" /> </head> <body ng-app="AngularReactTest" ng-controller="TestController"> <react-test monkey></react-test> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"> </script> <script src="https://fb.me/react-0.13.3.js"></script> <script> var ReactClass = React.createClass({ displayName: 'ReactClass',render: function () { return ( React.DOM.div({ 'data-ng-monkey': '' },null) ) } }); angular .module('AngularReactTest',[]) .controller('TestController',[function () { }]) .directive('reactTest',function () { return { restrict: 'E',link: function (scope,el,attrs) { var test = React.createElement(ReactClass,null,null); React.render(test,el[0],null); } } }) .directive('ngMonkey',function () { return { restrict: 'A',attrs) { alert('In ngMonkey link function...making my head hurt...'); },} }); </script> </body> </html>
这是渲染结果:
<ReactTest> <div data-ng-monkey></div> </ReactTest>
解决方法
我知道这是一个古老的主题,但我认为这个解决方案可以帮助别人
React.createClass({ compileDirective: function () { $compile(this.refs.monkey)($scope); },componentDidMount: function () { this.compileDirective(); },componentDidUpdate: function () { this.compileDirective(); },render: function () { return ( <div> <monkey ref="monkey"></monkey> </div> ); } });