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

查看:32
本文介绍了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.

我熟悉 Chrome 调试扩展React,但并非在所有浏览器中都可用.结合 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?

推荐答案

我刚刚通读了文档,我相信没有一个对外公开的 API 会让你直接进入并通过 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天全站免登陆