react怎么销毁组件?

最近突然来了兴致研究react,在研究react的JSX语法,组件时,觉得没有什么问题,都挺好理解的,但是看到生命周期这一部分时,发现官网给出的声明周期事件有一个怎么都不能主动触发到,后来在网上查了查,网上都只给出了声明周期的概念,没有人去真正测试过如何触发React组件的销毁。
于是只能自己动手,分析React对象和ReactDom对象,经过不停测试,终于让我发现主动销毁组件的方法了,如下:
ReactDOM.unmountComponentAtNode(document.getElementById("example"));注:example是该实例的根节点。
下面是完整代码示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Hello React</title>
<script src="/react/system/lib/react/react.min.js"></script>
<script src="/react/system/lib/react/react-dom.min.js"></script>
<script src="/react/system/lib/react/browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<!-- 脚本类型babel,声明代码里有jsx语法,交由浏览器的browser去解析 -->
<script type="text/babel">
var Button = React.createClass({
getInitialState: function() {
return {
data:'msg'
};
},
setNewNumber: function() {
this.setState({data: ''})
},
render: function () {
return (
<div>
<button onClick = {this.setNewNumber}>INCREMENT</button>
<Content myNumber = {this.state.data} ref="content"></Content>
</div>
);
},
componentWillUnmount:function() {
console.log('111Component WILL UNMOUNT!')
}
});
var Content = React.createClass({
componentWillMount:function() {
console.log('Component WILL MOUNT!')
},
componentDidMount:function() {
console.log('Component DID MOUNT!')
},
componentWillReceiveProps:function(newProps) {
console.log('Component WILL RECEIVE PROPS!')
},
shouldComponentUpdate:function(newProps, newState) {
return true;
},
componentWillUpdate:function(nextProps, nextState) {
console.log('Component WILL UPDATE!');
},
componentDidUpdate:function(prevProps, prevState) {
console.log('Component DID UPDATE!')
},
componentWillUnmount:function() {
console.log('Component WILL UNMOUNT!')
},
render: function () {
return (
<div>
<h3>{this.props.myNumber}</h3>
</div>
);
}
});
var aa = ReactDOM.render(
<div>
<Button />
</div>,
document.getElementById('example')
);
/**
** 在控制台执行下面语句即可看到组件销毁事件被触发了
** ReactDOM.unmountComponentAtNode(document.getElementById("example"));
**/
</script>
</body>
</html>
标签: