首页 > 解决方案 > React:如何根据路线更改页脚组件的位置

问题描述

我有一个简单的页脚组件。它用于关于和支持页面。position在我的 sass中,我已将relative.

我想position根据路线改变它。如果是/about则位置:相对,/support然后是位置:固定。

有可能实现这一目标吗?

function GeneralFooter() {
  return (
    <div class="container">
      <div class="row">
        <div class="col-lg-4 col-md-4 col-sm-6 col-xs-6">
          <div class="footer-pad">
            <ul class="list-unstyled">
              <li>
                <a
                  className="nav-link"
                  href="*"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  Help
                </a>
              </li>
            </ul>
          </div>
        </div>
        <div class="col-lg-4 col-md-4 col-sm-6 col-xs-6">
          <div class="footer-pad">
            <ul class="list-unstyled">
              <li className="nav-item">
                <NavLink to="/about" className="nav-link">
                  <span>About</span>
                </NavLink>
              </li>
            </ul>
          </div>
        </div>
        <div class="col-lg-4 col-md-4 col-sm-6 col-xs-6">
          <div class="footer-pad">
            <ul class="list-unstyled">
              <li className="nav-item">
                <NavLink to="/support" className="nav-link">
                  <span>Support</span>
                </NavLink>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}

标签: reactjsreact-routerstyles

解决方案


我不确定您是否正在使用任何库,但如果没有,您可以使用以下代码。

使用style道具:

function GeneralFooter() {
  const location = useLocation();
  const pathName = location.pathname;

  return (
    <div 
      className="container" 
      style={{ 
        position: pathName === '/about' ? 'relative' : pathName === '/support' ? 'fixed' : 'inherit' 
      }}
    >
      ...

使用className道具

.footer--about {
  position: relative;
}

.footer--support {
  position: fixed;
}
function GeneralFooter() {
  const location = useLocation();
  const pathName = location.pathname;
  const extraClassName = pathName === '/about' ? 'footer--about' : pathName === '/support' ? 'footer--support' : '';

  return (
    <div 
      className={`container ${extraClassName}`}
    >
      ...

使用classNames依赖项:

function GeneralFooter() {
  const location      = useLocation();
  const rootClassName = classNames('container', {
    'footer-about': location.pathname === '/about',
    'footer-support': location.pathname === '/support',
  });

  return (
    <div className={rootClassName}>
      ...

推荐阅读