[英]How to hide a button component on a particular route in 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
值,因為它對於所有其他頁面總是正確的,
我將通過查看路線上的路徑名來檢查當前頁面,如果路線有詳細信息,則isBookDetailsPage
為true
,否則為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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.