<!DOCTYPE html>
<html>
<head>
<meat charset="UTF-8">
<title>getSnapshotBeforeUpdate使用场景</title>
<style>
.list {
width: 200px;
height: 150px;
background-color: skyblue;
overflow: auto;
}
.news {
height: 30px;
}
</style>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="test"></div>
<!-- 核心库 -->
<script type="text/javascript" src="../js/react.development.js"></script>
<!-- react-dom,操作dom -->
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<!-- 引入babel,jsx转为js -->
<script type="text/javascript" src="../js/babel.min.js"></script>
<!-- 此处一定要写babel -->
<script type="text/babel">
//1.创建组件
class NewsList extends React.Component{
state = {newsArr:[]}
componentDidMount(){
setInterval(() => {
//获取原状态
const {newsArr} =this.state
//模拟一条新闻
const news = '新闻'+(newsArr.length+1) //从1开始
//更新状态
this.setState({newsArr:[news,...newsArr]})
},1000);
}
getSnapshotBeforeUpdate(){
return this.refs.list.scrollHeight
}
componentDidUpdate(preProps,preState,height){
this.refs.list.scrollTop += this.refs.list.scrollHeight - height //refs指ref="list"
}
render(){
return(
<div className="list" ref="list">
{
this.state.newsArr.map((n,index)=>{
return <div key={index} className="news">{n}</div>
})
}
</div>
)
}
}
//2.渲染组件到页面
ReactDOM.render(<NewsList/>, document.getElementById("test"));
</script>
</body>
</html>
================