<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</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://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class Life extends React.Component{
constructor (props){
super(props)
this.state={
opacity:1
}
this.remove = this.remove.bind(this)
}
componentDidMount() {
this.timer = setInterval(
()=>{
let {opacity} = this.state
opacity -=0.1
if(opacity<=0){
opacity=1
}
this.setState({opacity})
},200
)
}
remove(){
ReactDOM.unmountComponentAtNode(document.getElementById('app') )
}
componentWillUnmount(){
// 清理定时器
clearInterval(this.timer)
}
render(){
const {opacity} = this.state
console.log(this)
return(
<div>
<h3 style={{opacity:opacity}}>{this.props.msg}</h3>
<button onClick={this.remove}>删除</button>
</div>
)
}
}
ReactDOM.render(<Life msg='react太难了'/>,document.getElementById('app') )
</script>
</body>
</html>
react定时器
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。