Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Unmounting React.js node

I'm trying to unmount a React.js node with this._rootNodeID

 handleClick: function() {

        React.unmountComponentAtNode(this._rootNodeID)

 }

But it returns false.

The handleClick is fired when I click on an element, and should unmount the root-node. Documentation on unmountComponentAtNode here

I've tried this as well:

React.unmountComponentAtNode($('*[data-reactid="'+this._rootNodeID+'"]')[0])

That selector works with jQuery.hide(), but not with unmounting it, while the documentation states it should be a DOMElement, like you would use for React.renderComponent

After a few more tests it turns out it works on some elements/selectors.

It somehow works with the selector: document.getElementById('maindiv'), where maindiv is an element not generated with React.js, and just plain html. Then it returns true.

But as soon as I try and select a different ElementById that is generated with React.js it returns false. And it wont work with document.body either, though they all essentially return the same thing if I console.log them (getElementsByClassName('bla')[0] also doesn't work)

There should be a simple way to select the node via this, without having to resort to jQuery or other selectors, I know it's in there somewhere..

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Unmount components from the same DOM element that you mount them in. So if you did something like:

ReactDOM.render(<SampleComponent />, document.getElementById('container'));

Then you would unmount it with:

ReactDOM.unmountComponentAtNode(document.getElementById('container'));

Here is a simple JSFiddle where we mount the component and then unmount it after 3 seconds.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...