本文是学习React笔记,对应视频为:https://www.bilibili.com/video/BV1oW41157DY 的 14 - 16 节。
生命周期
需求:自定义组件
1. 让指定的文本做显示/隐藏的动画
2. 切换时间为2s
3. 点击按钮从界面中移除组件界面
重要的钩子
1. render() 初始化渲染或更新渲染调用
2. componentDidMount() 开启监听,发送ajax请求
3. componentWillUnmount() 做一些收尾工作,如清理定时器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lifecycle</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
<script src="babel.min.js"></script>
</head>
<body>
<div id="life"></div>
<script type="text/babel">
class Life extends React.Component {
constructor(props) {
super(props);
//初始化状态
this.state = {
opacity: 1
}
this.distroyComponent = this.distroyComponent.bind(this)
}
distroyComponent() {
ReactDOM.unmountComponentAtNode(document.getElementById('life'))
}
componentDidMount() {
//启动循环定时器
this.intervalId = setInterval(function () {
console.log('定时器执行了')
let {opacity} = this.state;
opacity -= 0.1
if (opacity <= 0) {
opacity = 1;
}
this.setState({
opacity: opacity
});
}.bind(this), 200);
}
componentWillUnmount() {
//清理定时器
clearInterval(this.intervalId)
}
render() {
const {opacity} = this.state;
return (
<div>
<h2 style={{
opacity: opacity
}}>{this.props.msg}</h2>
<button onClick={this.distroyComponent}>移除</button>
</div>
)
}
}
ReactDOM.render(<Life msg="React!!"/>, document.getElementById('life'));
</script>
</body>
</html>