window.resize does not apply to dom monitoring.
ResizeObserver
The ResizeObserver interface monitors changes in the size of the Element's content box or border box , or SVGElement's bounds .
method
ResizeObserver.disconnect()
cancels all listening to Element on a particular observer target.
ResizeObserver.observe()
starts monitoring the specified Element.
ResizeObserver.unobserve()
ends the monitoring of the specified Element.
Monitor a dom when the page is loaded
const theResizeObserver = new ResizeObserver(this.handleResize);
theResizeObserver.observe(
document.getElementsByClassName("leftSpanRightBoix")[0]
);
Cancel the listener when the page is destroyed
theResizeObserver.unobserve(
document.getElementsByClassName("leftSpanRightBoix")[0]
);
// Callback function triggered by this element
handleResize = (dom) => {
// 我自己的处理逻辑
// ...
const height = dom[0].contentRect.height;
console.log(height, "aaa=========");
if (height > 40) {
!this.state.isShowLine &&
this.setState({
isShowLine: true,
});
} else {
if (this.state.isShowLine !== false) {
this.setState({
isShowLine: false,
});
}
}
};
Reference document: https://developer.mozilla.org/zh-CN/docs/Web/API/Resize_Observer_API