带有窗口resize()的动态height()

时间:2018-12-14 07:11:47

标签: jquery reactjs

我正在执行需要在ReactJS中实现以下jquery函数的任务。我找不到任何解决方案。

$(window).resize(function() {
    $('#content').height($(window).height() - 46);
});

$(window).trigger('resize');
html, body {
    width:100%;
    height:100%;
}

.bg {
    width:315px;
    height:23px;
    margin:0 auto;
    text-indent:9000px;
}

#bg1 {background:url(http://placehold.it/200x300) 0 50% no-repeat;}
#bg2 {background:url(http://placehold.it/200x300) 0 50% no-repeat;}

#content {
    width:450px; 
    margin:0 auto;
    text-align: center;
    border: 1px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="bg1" class="bg">top</div>
    <div id="content">
        Content
    </div>
<div id="bg2" class="bg">bottom</div>

2 个答案:

答案 0 :(得分:0)

您可以在LifeCycle方法中使用Javascript来做到这一点。

componentDidMount() {
    window.addEventListener("resize", this.updateDimensions);
}
componentWillUnmount() { /* Make sure you remove all the listeners inside willUnmount method */
    window.removeEventListener("resize", this.updateDimensions);
}
updateDimensions = () => {
    /* Your code to set the properties go here */
}

此外,您可以尝试避免通过updateDimensions方法直接更改DOM。您可以使用refs,也可以在状态上使用property,其值将在updateDimensions方法内更新。然后,您可以在需要更改高度的组件中将属性设置为style

答案 1 :(得分:0)

由于您所做的计算是固定的,并且取决于视口的高度,因此我会单独使用CSS。

#content{
    height: calc(100vh - 46px);
}

更新的代码

html, body {
    width:100%;
    height:100%;
    margin:0;
}

.bg {
    width:315px;
    height:23px;
    margin:0 auto;
    text-indent:9000px;
    overflow:hidden;
}

#bg1 {background:url(http://placehold.it/200x300) 0 50% no-repeat;}
#bg2 {background:url(http://placehold.it/200x300) 0 50% no-repeat;}

#content {
    width:450px; 
    margin:0 auto;
    text-align: center;
    border: 1px solid blue;
    
    height: calc(100vh - 46px);
}
<div id="bg1" class="bg">top</div>
    <div id="content">
        help me. seriously.
    </div>
<div id="bg2" class="bg">bottom</div>

相关问题