正如其他已经提到的,您需要componentWillUnmount。
这是 React 中的一个简单示例(我在其中添加了一些注释以了解正在发生的事情):
var Button = React.createClass({
componentWillUnmount: function(){
// console will show this message when compoent is being Unmounted("removed")
console.log('Button removed');
},
render() {
return <h1 ref='button_node'>
<ReactBootstrap.Button bsStyle="success">Red</ReactBootstrap.Button>
</h1>;
}
});
var RemoveButton = React.createClass({
getInitialState: function() {
// this state keep tracks if Button removed or not
//(you can use it for some redrawing or anything else in your code)
return {buttonMounted: true}
},
mountRedButton: function(){
ReactDOM.render(<Button/>, document.getElementById('button'));
this.setState({buttonMounted: true});
},
unmountRedButton: function(){
ReactDOM.unmountComponentAtNode(document.getElementById('button'));
this.setState({buttonMounted: false});
},
render() {
return <h1>
//based on condition if Button compoennt removed or not we show/hide different buttons
{ this.state.buttonMounted ? <ReactBootstrap.Button onClick={this.unmountRedButton } bsStyle="danger">Remove Red Button!</ReactBootstrap.Button> : null}
{ this.state.buttonMounted ? null :<ReactBootstrap.Button onClick={this.mountRedButton } bsStyle="success">Add Red Button!</ReactBootstrap.Button> }
</h1>;
}
});
// mount components
ReactDOM.render(<Button/>, document.getElementById('button'));
ReactDOM.render(<RemoveButton/>, document.getElementById('remove'));
这是JSFiddle上的完整工作示例
关于“plain javascript”——你已经在使用 React JS,我的例子是基于 React 和 ReactDom,仅此而已(实际上还有 react-bootstrap,我只为漂亮的按钮添加了它,它不是必需的全部)
更新:
MutationObserver 的使用怎么样?如果您需要一段时间来删除 DOM 中的节点,但在删除节点之前触发 componentWillUnmount(这对您来说似乎不合适),您可以使用它。按照我的按钮示例:
var removalWatcher = new MutationObserver(function (e) {
var removalTimeStamp = '[' + Date.now() + '] ';
if (e[0].removedNodes.length) {
console.log('Node was removed', e[0].removedNodes, 'timestamp:', removalTimeStamp)
};
});
这是一个JsFiddle 更新示例。您可以比较 MutationObserver 和 React ComponentWillUnmount 打印到控制台的时间戳。