Angular2/4中如何在非常规调用的函数里引用组件变量?
这个问题我之前在项目里也遇到过!核心原因是zTree的回调函数默认的this指向不是你的Angular组件实例,导致拿不到组件里的变量。别担心,这里有几个简单有效的解决方案,结合你的代码给你演示:
方案1:用箭头函数捕获组件上下文
箭头函数会自动继承外部作用域的this,也就是你的Angular组件实例。你可以直接把点击回调改成箭头函数,或者提前把组件的this存成变量备用:
addHoverDom(treeId, treeNode) { // 可选:提前保存组件this到变量,避免混淆 const componentThis = this; let aObj = $("#" + treeNode.tId + "_a"); let addBtnId = "diy_add_" + treeNode.tId; let ztree = $.fn.zTree.getZTreeObj(treeId); if ($("#" + addBtnId).length == 0) { $("#" + addBtnId).bind("click", () => { // 这里的this或者componentThis都指向组件实例 console.log(this.yourComponentVariable); // 直接访问组件变量 console.log(componentThis.yourComponentMethod()); // 调用组件方法 }); // 你的其他zTree逻辑代码... } }
方案2:用bind()强制绑定组件上下文
如果你更习惯用普通函数作为回调,可以用bind()方法把组件的this绑定到回调函数上,确保回调内部的this指向组件:
addHoverDom(treeId, treeNode) { let aObj = $("#" + treeNode.tId + "_a"); let addBtnId = "diy_add_" + treeNode.tId; let ztree = $.fn.zTree.getZTreeObj(treeId); if ($("#" + addBtnId).length == 0) { $("#" + addBtnId).bind("click", function() { // 此时this已经是组件实例了 console.log(this.yourComponentVariable); this.yourComponentMethod(); }.bind(this)); // 关键:把组件的this绑定到这个回调函数 // 你的其他zTree逻辑代码... } }
方案3:把回调定义为组件的箭头函数方法
如果你的addHoverDom本身是组件的类方法,可以把点击回调单独定义成组件的箭头函数成员,这样它天然就拥有组件的上下文:
@Component({ selector: 'app-your-tree', templateUrl: './your-tree.component.html' }) export class YourTreeComponent { // 组件变量 yourComponentVariable = "这是我的组件变量"; // 定义箭头函数形式的回调方法 private handleAddNodeClick = () => { console.log(this.yourComponentVariable); this.yourComponentMethod(); }; addHoverDom(treeId, treeNode) { let aObj = $("#" + treeNode.tId + "_a"); let addBtnId = "diy_add_" + treeNode.tId; let ztree = $.fn.zTree.getZTreeObj(treeId); if ($("#" + addBtnId).length == 0) { $("#" + addBtnId).bind("click", this.handleAddNodeClick); // 你的其他zTree逻辑代码... } } // 组件方法 private yourComponentMethod() { console.log("调用了组件方法!"); } }
小提醒:虽然用jQuery操作DOM是zTree的常规用法,但在Angular项目里,尽量优先考虑用Angular的视图操作方式哦~
内容的提问来源于stack exchange,提问作者Hal Shaw
相关产品推荐
相关产品推荐

