使用jQuery处理DOM,而无需更改react代码 [英] Manipulate the DOM using jQuery, without changing the react code

查看:35
本文介绍了使用jQuery处理DOM,而无需更改react代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要开发第三方插件,例如chrome扩展程序.因此,我绝对没有权限更改页面的javascript代码.我所能做的就是在页面外部添加内容.

Let's say I want to develop a third party plugin, like a chrome extension. So I will have absolutely no privilege to change the javascript code of the page. All I can do is add things external to the page.

因此,我将使用jQuery来操作DOM.但是,如果页面是通过react呈现的,那么我对DOM所做的操作将在react生命周期中被删除.我看到一些指导如何将jQuery集成到React应用程序的教程.但这不是我所需要的.有什么办法可以在不更改原始反应代码的情况下操纵DOM?就像注册侦听器到React引擎之类的东西一样?

So I would use jQuery to manipulate the DOM. But if the page is rendered by react, what I did to the DOM would be erased in the react lifecycle. I see some tutorials teaching how to integrate jQuery in to a react app. But this is not what I need. Is there any way to manipulate the DOM without changing the original react code at all? Like registering a listener to the react engine or something?

我所想到的就是使用setInterval或requestAnimationFrame循环来保持DOM的更改.但是我仍然想知道是否有更好的方法.

All I think of is to use a setInterval or requestAnimationFrame loop to keep the DOM changed. But I still want to know if there is a better way.

推荐答案

您可以使用

You can use MutationObserver to detect the moment DOM was modified and add your stuff again if it was removed.

let myStuff = $('<div>foo</div>');

const mo = new MutationObserver(() => {
  if (!document.contains(myStuff[0])) {
    insert();
  }
});

observe();

function insert() {
  mo.disconnect();
  myStuff.appendTo('.some.react.element');
  observe();
}

function observe() {
  mo.observe(document.body, {childList: true, subtree: true});
}

另一种高级方法是通过页面上下文中的 __ REACT_DEVTOOLS_GLOBAL_HOOK __ 插入React本身,React DevTools也使用它,请查找更多信息如果您不害怕深入自己的话,那就自己吧.

Another advanced approach is hooking into React itself via __REACT_DEVTOOLS_GLOBAL_HOOK__ in page context, it's also used by React DevTools, look for more info yourself if you aren't afraid to delve into the depths.

这篇关于使用jQuery处理DOM,而无需更改react代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆