简体   繁体   English

如何从 react-router-doms 的渲染中传递道具?

[英]How do I pass props down from react-router-doms's render?

I am aware that to pass down props to my Routes I need to use the render.我知道要将道具传递给我的路线,我需要使用渲染。 For example:例如:

const BaseRouter = (props) => (

    <div>
        {console.log(props)} // this displays everything I need, including props.username
        <Route exact path='/room/' render={(props) => <Room {...props} />} />
    </div>
);

The problem is that inside my Room component, the only props passed down are history, location, and match (these come straight from react-router-dom).问题是在我的 Room 组件中,唯一传递的道具是历史、位置和匹配(这些直接来自 react-router-dom)。

I have also tried manually passing the props needed down:我也尝试过手动传递所需的道具:

<Route exact path='/room/' render={(props) => <Room {...props} username={props.username} />} />

But inside Room, I still get undefined for props.username.但在 Room 内,我仍然无法为 props.username 定义。 Any ideas?有任何想法吗?

You need to give a different name to you variables.你需要给你的变量一个不同的名字。 Doing render={(props) => <Room {...props} /> will always pass the router props, that is why props.username is undefined.执行render={(props) => <Room {...props} />将始终传递路由器 props,这就是未定义props.username的原因。

const BaseRouter = (props) => (

    <div>
        <Route exact path='/room/' render={(routeProps) => <Room {...routeProps} {...props} />} />
    </div>
);

Route component takes children as well. Route 组件也需要子组件。

 const BaseRouter = (props) => ( <div> {console.log(props)} // this displays everything I need, including props.username <Route exact path='/room/'> <Room {...props}/> </Route> </div> );

In Room component you can use useHistory, useLocation and useRouteMatch hooks.Room组件中,您可以使用 useHistory、useLocation 和 useRouteMatch 挂钩。 If Room is class based component then withRouter HOC is also useful.如果Room是基于 class 的组件,那么 withRouter HOC 也很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM