只是为了抛出另一个取自this blog的替代方案。
export class ChildComponent implements OnChanges {
/* METHOD THREE
* Using a decorator
*/
@OnChange<number>((value, simpleChange) => {
console.log('OnChange decorator methodThree', value)
})
@Input()
methodThree: number;
}
装饰器
export interface SimpleChange<T> {
firstChange: boolean;
previousValue: T;
currentValue: T;
isFirstChange: () => boolean;
}
export function OnChange<T = any>(callback: (value: T, simpleChange?: SimpleChange<T>) => void) {
const cachedValueKey = Symbol();
const isFirstChangeKey = Symbol();
return (target: any, key: PropertyKey) => {
Object.defineProperty(target, key, {
set: function (value) {
// change status of "isFirstChange"
if (this[isFirstChangeKey] === undefined) {
this[isFirstChangeKey] = true;
} else {
this[isFirstChangeKey] = false;
}
// No operation if new value is same as old value
if (!this[isFirstChangeKey] && this[cachedValueKey] === value) {
return;
}
const oldValue = this[cachedValueKey];
this[cachedValueKey] = value;
const simpleChange: SimpleChange<T> = {
firstChange: this[isFirstChangeKey],
previousValue: oldValue,
currentValue: this[cachedValueKey],
isFirstChange: () => this[isFirstChangeKey],
};
callback.call(this, this[cachedValueKey], simpleChange);
},
get: function () {
return this[cachedValueKey];
},
});
};
}
此方法使用typescript decorator。恕我直言,装饰者可能会留下,但...
装饰器是一项实验性功能,可能会在未来的版本中发生变化