0

我想从 JavaScript 开始创建自己的 componentDidUpdate() 生命周期方法。React 是如何做到的?Vue.JS 是如何创建自己的生命周期方法的。我尝试研究 Vue.JS 缩小版,但它让我很困惑。如果可以请告诉我,谢谢。类似于下面的东西。

Element.prototype.whenUpdated = function() {
  /*some codes here that runs when the HTML element is updated*/
}
4

1 回答 1

1

componentDidUpdate只有在视图框架的上下文中才有可能(并且只有真正有意义),其中元素的状态保存在框架内,并且对视图的更改源于对框架状态的更改。对框架状态的更改通过框架方法公开。

这是一个小例子,说明类似的情况:

// Framework code
class CustomDiv {
  constructor(sel, text) {
    this.container = document.querySelector(sel);
    this.text = text;
    this.update();
  }
  setText(newText) {
    this.text = newText;
    this.update();
  }
  update() {
    this.container.textContent = this.text;
    this.updateCallback?.();
  }
}

// Interact with the framework...
const customDiv = new CustomDiv('.container', 'initial text');
customDiv.updateCallback = () => {
  console.log('updated!');
};
setTimeout(() => {
  customDiv.setText('new text');
}, 1000);
<div class="container"></div>

虽然确实存在 MutationObserver,它可以观察原生元素的内容和属性等的变化,但这是完全不同的事情。

于 2021-04-02T04:55:33.733 回答