reactjs - React 组件如何通过路由调用参数?
问题描述
RouteParamPage.tsx 是一个 React 组件,可以通过路由器使用 URL 参数。这是工作。调用是这样的:
<Route path={"/p2/:lastname"} component={RouteParamPage}/>
ParamPage.tsx 组件在签名中有一个参数。我可以在没有这样的路由器的情况下调用这些组件:
<ParamPage label={"with params V2"}/>
问题是,如何在 Route 中调用 ParamPage.tsx 组件?这不起作用:
<Route path={"/p1"} component={ParamPage label={"with params V2"}}/>
有人有什么想法吗?
----------------- RouteParamPage.tsx --------------
import React from 'react';
import { useParams } from 'react-router-dom';
interface RouteParams {
lastname: string
}
export default function RouteParamPage() {
const params = useParams<RouteParams>();
return (
<React.Fragment>
<h1>{params.lastname}</h1>
</React.Fragment>
)
}
----------------- ParamPage.tsx --------------
import React from 'react';
type childProps = {
label: string,
}
export default function ParamPage( data: childProps ) {
return (
<React.Fragment>
<h1>{ data.label }</h1>
</React.Fragment>
)
}
----------------- Main.tsx --------------
import React from 'react';
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";
import Home from "./Home";
import ParamPage from "./ParamPage";
import RouteParamPage from "./RouteParamPage";
export default function Main() {
return (
<React.Fragment>
<ParamPage label={"with params V2"}/> {/*<<<<this works*/}
<Router>
<Switch>
<Route path={"/"} exact component={Home}/>
<Route path={"/p1"} component={ParamPage label={"with params V2"}}/> {/*<<< That doesn't work:*/}
<Route path={"/p2/:lastname"} component={RouteParamPage}/>
</Switch>
</Router>
</React.Fragment>
)
}
解决方案
您应该使用渲染道具将参数传递给由组件渲染的Route
组件,如下所示
<Route path="/p1" render={(routeProps) => {
return <ParamPage label={"with params V2"}} {...routeProps}/>
}} />
要了解有关查看 React渲染道具文档的更多信息
推荐阅读
- node.js - 将图像上传到 Azure Blob 存储
- ubuntu - ubuntu apt-get 未满足的 libsmbios2v5 和 libsmbios2 依赖项
- json - 如何使用 jq 提取此 JSON 片段中 href 的值?
- ruby-on-rails - Rails 活动模型序列化程序如何处理嵌套资源?
- mysql - 点燃和参考表
- html - 滤镜亮度过渡 CSS3
- user-interface - Inkscape的主题定制
- javascript - 使用 Javascript 数组创建 HTML 表
- sonarqube - Sonarqube 扫描仪错误 DirectoryNotEmptyException
- php - OTP 硬件符合 OATH TOTP 和 php 库