首页 > 解决方案 > 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>
    )
}

标签: reactjstypescriptreact-router-dom

解决方案


您应该使用渲染道具将参数传递给由组件渲染的Route组件,如下所示

<Route path="/p1" render={(routeProps) => {
    return <ParamPage  label={"with params V2"}} {...routeProps}/>
}} />

要了解有关查看 React渲染道具文档的更多信息


推荐阅读