Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
910 views
in Technique[技术] by (71.8m points)

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

This works perfectly fine in React version 0.12:

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

The variable dom gets the actual DOM node for the rendered component. However, converting this to React 0.13 does not work as expected:

componentDidMount: function () {
    var dom = React.findDOMNode();
    // dom is undefined
}

I tried React.findDOMNode(this) which does not work either. Basically I'm just trying to fetch the top-level dom node rendered by the render function without using a ref. Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update React v0.14+

In React v0.14+ this has changed, you should now use the react-dom module:

import ReactDOM from 'react-dom';

ReactDOM.findDOMNode(this);

ES6

class Test extends React.Component {
  componentDidMount() {
    const element = ReactDOM.findDOMNode(this);
    console.log(element);
    alert(element);
  }
  
  render() {
    return (
      <div>test</div>
    );
  }
}

ReactDOM.render(<Test />, document.getElementById('r'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="r" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...