在路由定义中实例化组件时如何引用路径中的参数?到达路由器v4

How to refer to param in path when instantiating component in route definition? reach router v4

目前,在我的 route.tsx 中,我定义了以下内容:

<Route exact={true} path="/test/:id" component={Test} />

测试组件实际上接受了一个名为 id 的属性。

<Test id="23232"/>

您将如何定义访问“:id”的路由,以便它可以传入而不是必须访问测试组件中的参数。

类似于

<Route exact={true} path="/test/:id" component={(props)=>{ <Test id={props.match.params.id} />}} />

这可能吗?

谢谢, 德里克

是的,这是可能的。

但是,您只需稍微调整一下语法即可删除多余的大括号组:

<Route exact={ true } path="/test/:id" component={ (props) => <Test id={ props.match.params.id } /> } />

您可能还想使用 render 而不是 component:

<Route exact={ true } path="/test/:id" render={ (props) => <Test id={ props.match.params.id } /> } />

来自文档:

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component attribute, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).

https://reacttraining.com/react-router/web/api/Route/component