问题:运用antd的Modal对话框开发时,在页面中点击按钮,弹出框出现后,默认给body添加了overflow:hidden;导致页面固定导航栏宽度有所改变,页面发生晃动。
问题截图:
原始样式
点击按钮后:
右边的滚动条消失,顶部导航栏被“拉开”。
而查看知乎的主页却没有上述问题,导航栏不会随滚动条的消失而被拉开。
解决办法:考虑动态给导航栏动态设置宽度,在生命周期中监听窗口滚动事件,判断有无滚动条,再减去滚动条的宽度。
componentDidMount(){
window.addEventListener('resize',this.handlHeight)
}
handlHeight=()=>{
const scrollWidth = document.body.clientWidth
let width= `${scrollWidth -18}px`
this.setState({
width
})
}
hasScrollbar=()=>{
return document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight);
}
附:在模拟实现时,react动态添加样式的方法
hindleClick(){
if (this.state.visity) {
document.body.removeAttribute("class","add_bg");
}else{
document.getElementsByTagName("body")[0].className="add_bg";
}
this.setState({
visity:!this.state.visity
})