[英]How can i pass a value from a component to another component in ReactJS
[英]How I can pass a value to a controller using a component?
我正在尝试通过组件将值传递给我的控制器,但是我仍然收到此未定义的消息。 我想念什么吗?
myhtml.html
<my-component item="value1"></my-component>
<my-component item="value2"></my-component>
<my-component item="value3"></my-component>
mycomponent.js
angular
.module('mycomponent.component', [
'mycomponent.controller'
])
.component('myComponent', {
templateUrl: 'components/mycomp/mycomp.component.html',
controller: 'ComponentController',
controllerAs: 'componentVM',
replace: true,
bindings: {
item: '='
}
});
mycontroller.js
angular
.module('mycomponent.controller', [])
.controller('ComponentController', ComponentController);
ComponentController.$inject = [];
function ComponentController() {
var vm = this;
console.log('item value> ' + vm.item); // This is got undefined :(
}
如@mhodges的注释所建议,将所有逻辑放入$onInit
挂钩中。 当所有绑定初始化时, $onInit
作为组件生命周期的一部分被触发。
var self = this;
self.$onInit = function(){
console.log('item value> ' + self.item);
}
回到您的代码,如果value1
是原始类型,则应使用单向绑定@
(原始类型不能使用双向绑定,因为它们不是引用)
bindings: {
item: '@'
}
<my-component item="value1"></my-component>
在item
是对象的情况下,要使组件与外部环境脱钩,最好使用单向绑定<
,
bindings: {
item: '<'
}
这甚至会遵循针对基于组件的架构的Angular> 1.5准则。
从Angular 1.5 doc:
输入应使用<和@绑定。 <符号表示从1.5开始可用的单向绑定。 与=的区别在于,不监视组件范围内的绑定属性,这意味着,如果为组件范围内的属性分配新值,则不会更新父范围
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.