React - 从DOM元素获取组件以进行调试 [英] React - getting a component from a DOM element for debugging

查看:117
本文介绍了React - 从DOM元素获取组件以进行调试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在控制台中进行调试,React中是否有任何机制可以使用DOM元素实例来获取后备React组件?

For the purposes of debugging in the console, is there any mechanism available in React to use a DOM element instance to get the backing React component?

这个问题有先前在生产代码中使用它的上下文中被问到过。但是,我的重点是用于调试的开发版本。

This question has been asked previously in the context of using it in production code. However, my focus is on development builds for the purpose of debugging.

我熟悉针对React的Chrome调试扩展程序,但并非所有浏览器都提供此功能。结合使用DOM浏览器和控制台,可以很容易地使用'$ 0'快捷方式来访问有关突出显示的DOM元素的信息。

I'm familiar with the Chrome debugging extension for React, however this isn't available in all browsers. Combining the DOM explorer and console it is easy to use the '$0' shortcut to access information about the highlighted DOM element.

我想编写类似这样的代码调试控制台:
getComponentFromElement($ 0).props

I would like to write code something like this in the debugging console: getComponentFromElement($0).props

即使在React开发版本中,也没有机制可以使用元素的ReactId来获取组件?

Even in a the React development build is there no mechanism to use maybe the element's ReactId to get at the component?

推荐答案

我刚刚阅读了文档,并且afaik没有任何外部公开的API会让你直接进入in并按ID查找React组件。但是,您可以更新您的初始 React.render()调用并将返回值保留在某处,例如:

I've just read through the docs, and afaik none of the externally-exposed APIs will let you directly go in and find a React component by ID. However, you can update your initial React.render() call and keep the return value somewhere, e.g.:

window.searchRoot = React.render(React.createElement......

然后你可以引用searchRoot,直接查看它,或者使用 React.addons.TestUtils 遍历它。例如,这将为你提供所有组件:

You can then reference searchRoot, and look through that directly, or traverse it using the React.addons.TestUtils. e.g. this will give you all the components:

var componentsArray = React.addons.TestUtils.findAllInRenderedTree(window.searchRoot, function() { return true; });

有几种用于过滤此树的内置方法,或者您可以编写自己的函数以仅返回基于你写的一些支票的组件。

There are several built-in methods for filtering this tree, or you can write your own function to only return components based on some check you write.

关于TestUtils的更多信息: https://facebook.github.io/react/docs/test-utils.html

More about TestUtils here: https://facebook.github.io/react/docs/test-utils.html

这篇关于React - 从DOM元素获取组件以进行调试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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