为使用React的网站制作Chrome扩展程序。重新渲染后如何保持更改?

问题描述 投票:0回答:1

我希望我的扩展程序向页面添加元素。但该网站使用React,这意味着每次有更改时页面都会重新渲染,但没有我添加的元素。

我在很久以前建立的一些教程应用程序中只是熟悉React。

javascript reactjs google-chrome-extension
1个回答
0
投票

我实施@ wOxxOm的评论使用MutationObserver并且它运作良好。

  static placeAndObserveMutations (insertionBoxSelector) {
    let placer = new Placement ();
    placer.place(insertionBoxSelector);
    placer.observeMutations(insertionBoxSelector);

  }

  place (insertionBoxSelector) {
    let box = $(insertionBoxSelector)
    this.insertionBox = box; //insertionBox is the element that the content
    // will be appended to
    this.addedBox = EnterBox.addInfo(box); //addedBox is the content
// Worth noting that at this point it's fairly empty. It'll get filled by
// async ajax calls while this is running. And all that will still be there
// when it's added back in the callback later.
  }

  observeMutations(insertionBoxSelector) {
    let observer = new MutationObserver (this.replaceBox.bind(this));
// this.insertionBox is a jQuery object and I assume `observe` doesn't accept that
    let insertionBox = document.querySelector(insertionBoxSelector);
    observer.observe(title, {attributes: true});
  }

  replaceBox () {
    this.insertionBox.append(this.addedBox);
    _position (this.addedBox);
  }

据说有人建议在React节点(即body)上面添加内容,并且只是相对于窗口绝对定位添加的内容。因为这实际上解决了我在网站的某些页面上遇到的一个单独的问题,我可能会这样做。而且,它更简单。

但我认为这对于一个罕见的问题仍然是一个有趣的解决方案,所以我也想发布它。

© www.soinside.com 2019 - 2024. All rights reserved.