How do you inspect a react element's props & state in the console?

前端 未结 5 2043
暗喜
暗喜 2021-01-30 12:24

React Developer Tools give a lot of power to inspect the React component tree, and look at props, event handlers, etc. However, what I\'d really like to do is to be able to insp

相关标签:
5条回答
  • 2021-01-30 12:56

    Though the accepted answer works, and is a great method, in 2020 you can now do a lot of inspection without using the $r method. The Components tab of React DevTools will show you props and detailed state when you select the relevant component (make sure you're on the right level), as well as let you do other things like suspend it or inspect the matching DOM element (little icons in the top right).

    0 讨论(0)
  • 2021-01-30 13:03

    An answer to your question can be found here in a similar question I asked: React - getting a component from a DOM element for debugging

    I'm providing an answer here because I don't have the necessary reputation points in order to mark as duplicate or to comment above.

    Basically, this is possible if you are using the development build of react because you can leverage the TestUtils to accomplish your goal.

    You need to do only two things:

    • Statically store the root level component you got from React.render().
    • Create a global debug helper function that you can use in the console with $0 that accesses your static component.

    So the code in the console might look something like:

    > getComponent($0).props
    

    The implementation of getComponent can use React.addons.TestUtils.findAllInRenderedTree to search for match by calling getDOMNode on all the found components and matching against the passed in element.

    0 讨论(0)
  • 2021-01-30 13:03

    Assign the state or prop object to the window object:

    window.title = this.state.title
    

    And then from the dev tools console you can try different methods on the exposed object such as:

    window.title.length
    

    8

    0 讨论(0)
  • 2021-01-30 13:04

    Using React Developer Tools you can use $r to get a reference to the selected React Component.

    The following screenshot shows you that I use React Developer Tools to select a component (Explorer) which has a state-object callednodeList. In the console I can now simply write $r.state.nodeList to reference this object in the state. Same works with the props (eg.: $r.props.path)

    0 讨论(0)
  • 2021-01-30 13:10

    Open console (Firefox,Chrome) and locate any reactjs rendered DOM element or alternatively execute js script to locate it:

    document.getElementById('ROOT')
    

    Then check for element properties in object property viewer for attributes with name beginning like '__reactInternalInstace$....' expand _DebugOwner and see stateNode.

    The found stateNode will contain (if it has) 'state' and 'props' attributes which is used heavily in reactjs app.

    0 讨论(0)
提交回复
热议问题