React.js: The difference between findDOMNode and getDOMNode

后端 未结 2 623
野的像风
野的像风 2021-01-01 10:19

Could somebody tell me what\'s the difference between

React.findDOMNode(this.refs.email).value

and

this.refs.email.getDOMN         


        
相关标签:
2条回答
  • 2021-01-01 10:34

    The second one is the old API for accessing a refs DOM node, and the first one is the new way. So if you're using a recent version of React, you should use the first.

    0 讨论(0)
  • 2021-01-01 10:45

    component.getDOMNode() is deprecated as of React 0.13:

    Added new top-level API React.findDOMNode(component), which should be used in place of component.getDOMNode(). The base class for ES6-based components will not have getDOMNode. This change will enable some more patterns moving forward.

    via http://facebook.github.io/react/blog/2015/03/10/react-v0.13.html#new-features

    It will likely be removed in a future version of React (but don't quote me on that, because I can't find a good reference).


    EDIT: Updated to reflect React 0.14

    getDOMNode() throws a warning in 0.13 and 0.14, and it will be removed completely in 0.15:

    With each returned DOM node, we've added a getDOMNode method for backwards compatibility that will work with a warning until 0.15.

    via https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html#new-deprecations-introduced-with-a-warning

    Also note that calling findDOMNode or getDOMNode is no longer necessary for React DOM components as of 0.14:

    The other big change we’re making in this release is exposing refs to DOM components as the DOM node itself. That means: we looked at what you can do with a ref to a React DOM component and realized that the only useful thing you can do with it is call this.refs.giraffe.getDOMNode() to get the underlying DOM node. Starting with this release, this.refs.giraffe is the actual DOM node. Note that refs to custom (user-defined) components work exactly as before; only the built-in DOM components are affected by this change.

    via https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html#dom-node-refs


    Relevant code and commits from the React repo on GitHub:

    • https://github.com/facebook/react/blob/a6d03f36a4a9e7c1e6688bdba89656f2e20e7df8/src/modern/class/ReactComponent.js#L101-L104
    • https://github.com/facebook/react/commit/b46a6ce4bb8d6087ed424764f41fe4b8e248b3b4
    • https://github.com/facebook/react/commit/fb23276178b28fdcb75aa22be013a91755f7ad0a
    0 讨论(0)
提交回复
热议问题