React 0.13 this.getDOMNode() equivalent to React.findDOMNode()

后端 未结 5 2214
死守一世寂寞
死守一世寂寞 2020-12-13 04:29

This works perfectly fine in React version 0.12:

componentDidMount: function () {
    var dom = this.getDOMNode();
}

The variable dom

5条回答
  •  别那么骄傲
    2020-12-13 05:09

    For more complex elements like React components created on standard DOM elements refs give us only first DOM element ( root element of component ) so sometimes we need to find desired node inside it. Good example is Material-Ui TextField component and how we can get value from it.

    1.Required imports

    import React, { Component } from 'react';
    import TextField from 'material-ui/TextField';
    import ReactDOM from 'react-dom';
    

    2.Virtual dom and ref="variable"

     
    

    3.Query inside TextField:

    ReactDOM.findDOMNode(this.refs.title).querySelector("input").value
    

    or for multiline:

    ReactDOM.findDOMNode(this.refs.title).querySelector("textarea").value
    

    We start from TextField container and using standard DOM query querySelector get wanted input element. This solution is working with any complexed components, we always can query inside it. Tested on React (15.3.2).

提交回复
热议问题