reactjs - 有条件地在特定路线和视口高度上渲染组件
问题描述
目标:当在/
路线和视口高度超过 1000px 时,不渲染导航组件。
但是,该Navigation
组件应该在所有其他路由上呈现(例如,affiliate-code
、dashboard
、editor
等)。
任何想法我怎么能做到这一点?
{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}
/>
)
}
/>
)}
解决方案
好的,因为您正在使用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>
)
}
推荐阅读
- java - 在 Android OS 中的 DatePicker 中,Harmony OS 中 setFirstDayOfWeek() 的替代方法是什么?
- path - HAProxy - 无法更改后端服务器中的路径
- php - PHPCS 的 Git Pre-Commit 钩子在 Laravel 的 Windows 中给了我错误
- r - Shinyapps 部署错误:应用程序依赖于包“dplyr”但未安装
- python - 查找数据框中的所有转换
- react-native - 如何使用样式在本机反应中创建甘特图
- visual-studio - 在 VS Toolbox 中以不同的 DisplayName 显示组件
- apache-flink - StreamTableEnvironment 是否能够针对批处理流运行?
- visual-studio-code - 检查项目文件夹中所有资产的大小写敏感及其在程序中的声明
- flutter - 无法修复在颤振中不正确使用 ParentDataWidget