尝试在反应中使用 scrollHeight
Trying to use scrollHeight in react
谁能告诉我为什么我在 console.log heightSet 时会变得不确定?
componentDidMount() {
this.updateDimensions();
window.addEventListener('resize', this.updateDimensions.bind(this));
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions.bind(this));
}
updateDimensions() {
this.setState({ heightSet: document.scrollHeight });
console.log(document.clientHeight);
}
相同的 console.log 为 window.innerHeight 工作(clientHeight 也未定义)但我不想要内部高度我想要 scrollHeight。
谢谢
scrollHeight
是 Element
上的 属性 所以我猜你可能想要 document.body.scrollHeight
.
顺便说一句,每次调用 this.updateDimensions.bind(this)
都会得到一个新函数,因此您不能使用这种方法来添加和删除相同的事件侦听器。
您应该向 class 添加一个构造函数,其中包含以下内容:
constructor(props) {
super(props);
this.updateDimensions = this.updateDimensions.bind(this);
}
那你可以直接add/removethis.updateDimensions
:
componentDidMount() {
this.updateDimensions();
window.addEventListener('resize', this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions);
}
updateDimensions() {
this.setState({ heightSet: document.body.scrollHeight });
}
您可能想尝试使用 "scroll" 事件。
componentDidMount() {
this.updateDimensions();
window.addEventListener('scroll', this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.updateDimensions);
}
updateDimensions() {
this.setState({ heightSet: window.scrollY });
}
谁能告诉我为什么我在 console.log heightSet 时会变得不确定?
componentDidMount() {
this.updateDimensions();
window.addEventListener('resize', this.updateDimensions.bind(this));
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions.bind(this));
}
updateDimensions() {
this.setState({ heightSet: document.scrollHeight });
console.log(document.clientHeight);
}
相同的 console.log 为 window.innerHeight 工作(clientHeight 也未定义)但我不想要内部高度我想要 scrollHeight。
谢谢
scrollHeight
是 Element
上的 属性 所以我猜你可能想要 document.body.scrollHeight
.
顺便说一句,每次调用 this.updateDimensions.bind(this)
都会得到一个新函数,因此您不能使用这种方法来添加和删除相同的事件侦听器。
您应该向 class 添加一个构造函数,其中包含以下内容:
constructor(props) {
super(props);
this.updateDimensions = this.updateDimensions.bind(this);
}
那你可以直接add/removethis.updateDimensions
:
componentDidMount() {
this.updateDimensions();
window.addEventListener('resize', this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions);
}
updateDimensions() {
this.setState({ heightSet: document.body.scrollHeight });
}
您可能想尝试使用 "scroll" 事件。
componentDidMount() {
this.updateDimensions();
window.addEventListener('scroll', this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.updateDimensions);
}
updateDimensions() {
this.setState({ heightSet: window.scrollY });
}