我正在制作react redux应用程序.
当我添加元素时,我的视图变得更大(或者当我删除元素时,我的视图变得更小),但我无法正确地跟进.
我尝试使用scrollHeight来确定它应该具有的大小:
https://i.imgur.com/HGHJgub.gifv
这是我的代码:
constructor(props) {
super(props);
this.state = {
heightSet: 0,
};
this.updateDimensions = this.updateDimensions.bind(this);
}
componentDidMount() {
this.updateDimensions();
window.addEventListener('resize', this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions);
}
updateDimensions() {
this.setState({ heightSet: document.body.scrollHeight });
console.log(document.body.scrollHeight);
}
render() {
const divStyle = {
height: this.state.heightSet + 'px',
};
return (
<div style={divStyle}>
</div>
)
}
但所有这一切显然都被抛弃了.
我没有采取正确的方法.
它还涉及我的应用程序的另一个问题:
它知道向视图添加高度但不删除它.
有人知道为什么会有这种行为以及如何解决这个问题?
更新:
澄清真正的问题是当我点击“添加组件”并且滚动高度增加时,此解决方案没有对var进行任何更新.
总而言之,上述解决方案完全是垃圾.
我喜欢这个想法:Set color for extra page parts visible during rubber band scroll(是的,这是一个黑客,但我很好)
来自Shishir Arora和tksb
但它似乎不适用于现代浏览器(至少不是Chrome和最新Chrome的目标是我的应用程序N°1).
最佳答案 我重现了这个场景,我得到了这个.希望能帮助到你.
Why is it always growing?
在我的例子中,document.body.scrollHeight返回身体的高度及其边距(由于某种原因),因此每次设置组件高度时,它都会小于body的scrollHeight,并且身体随着子项的增长而增长随着调整大小,组件不断增长.
例如:
componentDidMount :
bodyHeight = 90 + 10 (a margin)
scrollHeight = 100
componentHeight = 100
newBodyHeight = 100 + 10
Resize:
bodyHeight = 100 + 10
scrollHeight = 110
componentHeight = 110
newBodyHeight = 110 + 10 , and so on.
How to remedy it?
您可以从scrollHeight中减去body的边距,或者从组件的子项高度计算高度.
我改变了这个:
updateDimensions() {
const margin = 16; // In my case was marginTop: 8px and marginBottom: 8px
const heightSet = document.body.scrollHeight - margin;
this.setState({ heightSet });
}