react窗口变化监听,需要在window对象中添加监听事件,事件中参数1位监听的事件,参数2为事件调用的方法
//窗口变化执行的方法
resizeWindow = ()=>{
let width = document.body.clientWidth;
if(width<=1000){
this.setState({
left:0
})
}else
{
this.setState({
left:parseInt((width-1000)/2)
})
}
}
//监听窗口变化
componentDidMount() {
window.addEventListener('resize', this.resizeWindow)
}
//析构窗口变化
componentWillUnmount() {
window.removeEventListener('resize', this.resizeWindow)
}