【问题标题】:Pass a function of window.onload inside styled-components在 styled-components 中传递 window.onload 的函数
【发布时间】:2018-06-06 07:06:36
【问题描述】:

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

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。

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

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

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

    使用view port高度

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

    【讨论】:

      【解决方案2】:

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

      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;
      `;
      

      【讨论】:

      • 这仍然返回height: px 样式的代码,它会呈现两次。第一个渲染是null 第二个渲染是getElementById的html代码
      【解决方案3】:

      虽然 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;
      `;
      

      【讨论】:

      • 这只会返回一个height: 0 样式的html devtools
      • 那你的window.innerHeight - document.getElementById('navigation-bar').clientHeight计算是错误的。
      • 这会返回一个数字。这是正确的,我不知道为什么该值不返回。 :(
      • 好的。我明白你的问题。现在的问题是——当你引用这个变量时,它还没有更新。将 panelHeight = window.innerHeight - document.getElementById('navigation-bar').clientHeight ; 语句放在 html 中第一个脚本标记的顶部。
      猜你喜欢
      • 2020-05-28
      • 2019-02-18
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 2023-03-24
      相关资源
      最近更新 更多