简体   繁体   English

如何在 react-router 中隐藏特定路线上的按钮组件

[英]How to hide a button component on a particular route in react-router

I am new to javascript and react.我是 javascript 的新手并做出反应。 I have done lots of Googling with no solution.我做了很多谷歌搜索没有解决方案。 I am trying to hide a button component on one of three pages/routes where it currently displays but when I try to do it, it hides on all the pages/routes.我试图在当前显示的三个页面/路线之一上隐藏一个按钮组件,但是当我尝试这样做时,它隐藏在所有页面/路线上。 Here is the code:这是代码:


const routes = [
  { 
    path: '/:bookId/details',
    title: 'Book Details', 
    component: BookDetailsPage, 
    hideButton: true 
  },
  { 
    path: '/:bookId', 
    title: 'Details', 
    component: BookPage,
    exact: true, 
    hideButton: false 
  },
  { 
    path: '/',
    title: 'Book',
    component: BookListPage, 
    hideButton: false
  }
];

const Page = (): React.ReactElement => {

  const isBookDetailsPage = routes[0].hideButton; //returns true

  return (
      <ContentMasterLayout
        title="Book"
        action={
          <Box display="flex">
            //this approach hides the button on all pages
            {!isBookDetailsPage &&
               <BookButton transactionId={match?.params.bookId} />}
          </Box>
        }
      >
        <LocalRouter routes={routes} />
      </ContentMasterLayout>
  );
};

Please any help would be appreciated.请任何帮助将不胜感激。 Thanks in advance提前致谢

I wouldn't use the hideButton value as it'll always be true for every other page,我不会使用hideButton值,因为它对于所有其他页面总是正确的,

I'll check the current page by looking at the pathname on the route and if the route has details then isBookDetailsPage is true and if not then it's false我将通过查看路线上的路径名来检查当前页面,如果路线有详细信息,则isBookDetailsPagetrue ,否则为false

So technically your code should look like this所以从技术上讲,你的代码应该是这样的

import { useLocation } from 'react-router-dom';

const Page = (): React.ReactElement => {
  
  const location = useLocation();
  
  // will be true/false
  const isBookDetailsPage = location.pathname.includes('details');

  return (
      <ContentMasterLayout
        title="Book"
        action={
          <Box display="flex">
            {!isBookDetailsPage &&
               <BookButton transactionId={match?.params.bookId} />}
          </Box>
        }
      >
        <LocalRouter routes={routes} />
      </ContentMasterLayout>
  );
};

In the example above, I used the useLocation() hook on react-router-dom V5.1, but you can also use props.location.pathname or the plain javascript window.location.pathname在上面的示例中,我在react-router-dom V5.1上使用了useLocation()挂钩,但您也可以使用props.location.pathname或普通的 javascript window.location.pathname

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM