[英]React How to Dynamically set offsetTop with height to a div
I am working on a dashboard part of a site and i am very new to reactjs.我正在处理网站的仪表板部分,我对 reactjs 非常陌生。 I am trying fit everything on a screen so that the user does not have to scroll expect for the table, i hope the code below defines the situation better.我正在尝试将所有内容都放在屏幕上,以便用户不必滚动表格,我希望下面的代码更好地定义了这种情况。
Here is my code:这是我的代码:
componentDidMount() {
this.tableHeightOffset();
}
tableHeightOffset() {
var getOffset = this.containerLine.offsetTop;
this.setState({ getOffset });
}
render() {
var findTableHeight = this.state.getOffset;
const tableHeight = {
height: 'calc(100vh - ' + findTableHeight + 'px' + ')'
}
return (
<div className="table-responsive" style={tableHeight} ref={el => this.containerLine = el}>
)
}
How do i get the offset to change when the browser resize or there is a update on the site ?当浏览器调整大小或网站上有更新时,如何更改偏移量?
Also I get the value on findTableHeight but it is not getting the offset from to the top of the window.我也得到了 findTableHeight 的值,但它没有得到从窗口顶部的偏移量。 I was suppose to get 161px of offsetTop but i am only getting 46px.我本来想得到 161px 的 offsetTop 但我只得到 46px。
You could define a resize listener to the window, in order to calculate the new hight.您可以为窗口定义一个调整大小的侦听器,以计算新的高度。 This could be done in componentDidMount():这可以在 componentDidMount() 中完成:
componentDidMount() {
window.addEventListener('resize', this.tableHeightOffset);
}
Don't forget to remove it before unmounting the component:在卸载组件之前不要忘记将其删除:
componentWillUnmount() {
window.removeEventListener('resize', this.tableHeightOffset);
}
Also offsetTop returns the offset from the parent. offsetTop 还返回与父级的偏移量。 In order to find the offset relative to the document, check this article: Finding element's position relative to the document为了找到相对于文档的偏移量,请查看这篇文章: 查找元素相对于文档的位置
在这里你有 api 来监听窗口大小的变化https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event使用它来动态改变你的偏移量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.