首页 > 解决方案 > 有条件地在特定路线和视口高度上渲染组件

问题描述

目标:当在/路线和视口高度超过 1000px 时,不渲染导航组件。

但是,该Navigation组件应该在所有其他路由上呈现(例如,affiliate-codedashboardeditor等)。

任何想法我怎么能做到这一点?

{user.uid && (
          <Route
            path={[
              "/affiliate-code",
              "/dashboard",
              "/editor",
              "/locked",
              "/saved",
              "/notifications",
              "/stats",
              "/create-page",
              "/",
            ]}
            component={() =>
              !["/send-invite", "/:id"].includes(window.location.pathname) && (
                <Navigation
                  key={window.location.pathname}
                  newNotification={newNotification}
                />
              )
            }
          />
        )}

标签: reactjs

解决方案


好的,因为您正在使用ReactRouter我建议使用它提供的钩子来反应性地检查当前路线。

另外,我建议你安装react-use,这样你就可以使用他们的钩子来被动地检查窗口高度。如果有人在初始加载后缩小屏幕,这将使您能够隐藏导航栏。

import React from 'react';
import { useLocation } from "react-router-dom";
import { useMedia } from 'react-use';

export const Navigation = ({ newNotification }) => {
    let { pathname } = useLocation();
    const isTallEnough = useMedia('(min-height: 1000px)');

    if (pathname !== '/' || !isTallEnough) return null;

    return (
        <div>
            ...your navigation
        </div>
    )
}

推荐阅读