【问题标题】:How to hide a button component on a particular route in react-router如何在 react-router 中隐藏特定路由上的按钮组件
【发布时间】:2021-03-19 17:24:20
【问题描述】:

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

如有任何帮助,我们将不胜感激。提前致谢

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom react-router-v4


    【解决方案1】:

    我不会使用 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

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 1970-01-01
      • 2021-08-05
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多