【问题标题】:React - Sticky Footer issue: Footer at bottom of App component; App component not at bottom of BodyReact - 粘页脚问题:App 组件底部的页脚;应用程序组件不在正文底部
【发布时间】:2018-09-03 21:40:57
【问题描述】:

我在反应中遇到了粘滞页脚的问题。我实现了在CSS Tricks上看到的flexbox解决方案,但是问题是footer在主App组件的底部,而App组件却不在body底部。这是一张说明这个问题的图片:

一些代码: 在我的 App 组件的渲染函数中,我返回了这个:

render() {
  return (
    <div className="App">
      <div className="all-but-footer">
        <Header />
          <main className="content">
            <Switch>
              <Redirect from="/" to="/bio" exact />
              <Route path="/bio" exact component={Bio} />
            </Switch>

            <Route path="/videos" exact component={Videos} />
            <Route path="/gallery" exact component={Gallery} />
            <Route path="/magnet-podcast" exact component={MagnetPodcast} />
          <Route path="/contact" exact component={Contact} />
        </main>
      </div>

    <Footer />
  </div>

当然,我会通过以下方式连接到根 div:

document.addEventListener('DOMContentLoaded', () => {

  const root = document.getElementById('root');

  ReactDOM.render(
    <Root />, root);
  registerServiceWorker();
});

在我的 index.html 中使用根 div,如下所示:

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <title>Louis Kornfeld</title>
  </head>
  <body>

    <div id="root"></div>

  </body>
</html>

在我的 CSS 中,我尝试将应用程序的高度设置为 100%,甚至尝试将 index.html 中的根 div 的高度设置为 100%。身体唯一的孩子是根 div,根 div 的孩子是 App,所以我认为将这些所有高度设为 100% 会拉伸组件,但没有任何效果。

有什么想法可以解决这个问题吗?

【问题讨论】:

  • 试试100vh,看看这个空白是什么。
  • 另外,你能否用以下元素的样式更新问题:body、root div、App div(如果它是 root div 的唯一子元素)和 App div 的子元素?这真的很有帮助!
  • 那么你想把页脚放在正文的底部吗?
  • @Aaqib 是的,我希望页脚位于页面底部,下方没有空间。
  • 我已经在下面回答了您的问题,您只需要使用 getElementByTagName 并将门户包裹在粘性页脚或您想要显示在底部的组件上

标签: html css reactjs footer sticky-footer


【解决方案1】:

通常,当您从组件的渲染方法返回元素时,它会作为最近父节点的子节点挂载到 DOM 中

如果你想将一个子元素插入到 DOM 中的不同位置,你可以使用React Portals

对我有用的是react-portal,您可以将其安装为项目依赖项npm install --save react-portal

在你的组件内部你可以:

    import { Portal } from 'react-portal';

    <Portal>
      This text is portaled at the end of document.body!
    </Portal>

    <Portal node={document && document.getElementById('youCanSelectAnyIdFromTheDOM')}>

    This text is portaled into San Francisco!
   </Portal>

你可以阅读更多关于react-portalHere

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2012-10-19
    • 2012-09-10
    相关资源
    最近更新 更多