如何通过函数传入的action参数动态调用对应对象属性?
实现方案
你原来的写法错误原因是:this.action的点语法会固定访问实例上名为action的属性,而非action参数值对应的属性。JS/TS中要动态访问对象属性,使用方括号语法即可:
最简修改版
onChange(event: any, id: number, action: string){ this[action][id]["Selected"] = true }
类型安全优化版(TS场景)
如果是TypeScript项目,上述写法可能会报类型错误,可以通过限定action的类型解决:
// 仅允许传入已定义的属性名 type AllowedAction = 'StatutoryReq' | 'StatutoryReqErp2007' onChange(event: any, id: number, action: AllowedAction){ this[action][id]["Selected"] = true }
兼容容错版
如果担心传入非法action值导致报错,可以加一层属性存在性判断:
onChange(event: any, id: number, action: string){ if (Object.prototype.hasOwnProperty.call(this, action) && this[action]?.[id]) { this[action][id]["Selected"] = true } }
内容的提问来源于stack exchange,提问作者Kestal。
相关产品推荐
相关产品推荐

