javascript - React Router v6 - 检查子元素是否处于事件状态/<Outlet/>会返回组件吗?

标签 javascript reactjs react-router-dom

美好的一天, 您能帮我解决有关react-router v6的嵌套元素(特别是子元素)的问题吗?

假设我有这个路由

<Routes>
    <Route path="customer" element={<CustomerIndex />} >
         <Route path=":customeId" element={<CustomerDetail />} />
         <Route path="create" element={<CustomerForm />} />
    </Route>
</Routes>

以及“CustomerIndex”组件

function CustomerPage(){
    const {customerId} = useParams();
    return (
            <>
               //.....Bla bla bla index table etc etc etc end of thinking capacity        
               <ComponentToDisplayModal display={Boolean(customerId)} >
                    <Outlet />
               </ComponentToDisplayModal>
            </>
         );
}

现在,如果我转到“/customer/3”,CustomerIndex 将显示模态组件 (display=true),因为“customerId”常量是由 useParams 定义的

但是,如果我想通过导航到“/customer/create”来显示“CustomerForm”组件,那么“ComponentToDisplayModal”当然不会显示,因为 customerId 为空。

所以,当然,我想要这个

const display = Boolean(customerId) || isAnyChildPath;
.....
<ComponentToDisplayModal {...{display}}>

现在,如果路径是“/customer/*”,我如何将“isAnyChildPath”常量设置为“TRUE”,如果路径是“/customer”,我如何将“isAnyChildPath”常量设置为“TRUE”,或者检查是否会返回组件(例如.“/customer/create”、“/customer/4”),还是不是(“/customer”)?

目前我只使用手动方法

const location = useLocation();
const display = Boolean(customerId) || location.pathname === "/customer/create"

但是我想了解是否存在更优雅的方法,以防将来我需要添加其他几个静态子项。

非常感谢。

最佳答案

我认为您可以使用 useMatch Hook 稍微简化子路由检查,并检查当前路径是否与任一子路由匹配,而不是通过任何路由路径参数进行测试。

useMatch

declare function useMatch<ParamKey extends string = string>(
  pattern: PathPattern | string
): PathMatch<ParamKey> | null;

Returns match data about a route at the given path relative to the current location.

这个想法是,当路由匹配时,返回定义的匹配对象,否则,如果不匹配,则返回 null

"/customer/:path" 可以匹配 "/customer/:id""/customer/create"

示例:

function CustomerPage(){
  const isMatch = useMatch("/customer/:path");

  return (
    <>
      //.....Bla bla bla index table etc etc etc end of thinking capacity        
      <ComponentToDisplayModal display={Boolean(isMatch)} >
        <Outlet />
      </ComponentToDisplayModal>
    </>
  );
}

Edit react-routger-v6-check-wether-child-element-is-active-outlet-would-return

关于javascript - React Router v6 - 检查子元素是否处于事件状态/<Outlet/>会返回组件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71494828/

相关文章:

javascript - React,将 onClick 事件直接添加到组件而不是在所述组件内渲染元素。

javascript - 通过 React 路由器将 prop 传递给组件

reactjs - 如果我升级react-router-dom,是否会遇到react和react-dom的兼容性问题?

javascript - 可拖动不显示可拖动项目并放置到错误的可放置项

Javascript requestAnimationFrame 微调器

reactjs - 如何在reactjs中使用azure ad应用身份验证2因素?

reactjs - 将 React.Js 添加到我的 Asp.net MVC 核心中,这可能/兼容吗?

javascript - this.props.history.push 在刷新后即可工作

javascript - 如何在悬停时更改屏幕区域的背景颜色

JavaScript: trim .toPrecision() 尾随零