微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我是 javascript 新手并做出反应。我已经做了很多谷歌搜索没有解决方案。我试图在它当前显示的三个页面/路由之一上隐藏一个按钮组件,但是当我尝试这样做时,它隐藏在所有页面/路由上。代码如下:


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>
  );
};

请任何帮助将不胜感激。提前致谢

解决方法

我不会使用 hideButton 值,因为它对于其他所有页面总是如此,

我将通过查看路线上的路径名来检查当前页面,如果路线有详细信息,则 isBookDetailsPagetrue,如果没有,则为 false

所以技术上你的代码应该是这样的

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>
  );
};

在上面的例子中,我在 react-router-dom V5.1, 上使用了 useLocation() 钩子,但你也可以使用 props.location.pathname 或普通的 javascript window.location.pathname

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。