在样式组件

时间:2018-06-06 07:06:37

标签: javascript css reactjs styled-components

我目前正在制作一个没有完整高度的侧边栏。我试图让标题的高度减去窗口屏幕的高度。

const setSidebarHeight = () => {
    return (window.onload = () => {
        if (document.getElementById('navigation-bar')) {
            return ( window.innerHeight - document.getElementById('navigation-bar').clientHeight );
        }
    });
}

const SideBarDiv = styled.div`
    color: #232323;
    background-color: #f4f3f4;
    float: left;
    position: relative;
    z-index: 100;
    height: ${setSidebarHeight()}px;
`;

我有一个关于将window.onload传递给css属性height的问题,当前代码在devtools中没有显示任何px。

请帮我解决这个问题。谢谢!

3 个答案:

答案 0 :(得分:1)

CSS#calc的帮助下,您可以进行动态高度计算。

使用view port身高

height : calc(100vh-20px) //20px height of header

答案 1 :(得分:0)

我不太明白你的问题,但我有更好的方法来做到这一点

const setSidebarHeight = () => {
 return (window.onload = () => {
  if (document.getElementById('navigation-bar')) {
   return ( window.innerHeight - document.getElementById('navigation-bar').clientHeight );
  }
 });
};

render() {
  <SideBarDiv height={this.setSidebarHeight()} />
}

const SideBarDiv = styled.div`
 // ....
 height: ${props => props.height}px;
`;

答案 2 :(得分:0)

虽然RIYAJ KHAN的回答引出了最好的方法,但我会回答你原来的问题。

您只需在onLoad方法中设置一个变量,并在组件字符串中引用它。

var panelHeight = 0;
window.onload = () => {
        if (document.getElementById('navigation-bar')) {
             panelHeight = window.innerHeight - document.getElementById('navigation-bar').clientHeight ;
        }
}

则...

const SideBarDiv = styled.div`
    color: #232323;
    background-color: #f4f3f4;
    float: left;
    position: relative;
    z-index: 100;
    height: ${panelHeight}px;
`;