React - getting a component from a DOM element for debugging

前端 未结 10 1053
广开言路
广开言路 2020-11-28 19:02

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 questi

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 19:37

    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......
    

    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.

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

提交回复
热议问题