简体   繁体   English

将道具传递到路由器内部的组件

[英]Passing props to component inside router

I want to use URL paths for my app. 我想为我的应用程序使用URL路径。 Currently I just render a Main component in app.js : 目前,我只是在app.js渲染一个Main组件:

render() {
  return (
    <Main 
      isLoggedIn={this.state.isLoggedIn}
      user={this.state.user}
      ... />
  )
}

(The props are a bunch of variables and functions) (道具是一堆变量和函数)

I tried using react-router but I don't understand how to send props to the child components. 我尝试使用react-router,但不了解如何将道具发送到子组件。

<Router history={browserHistory} >
  <Route path='/' component={Main}
    ... where to send props? />
  <Route path='join' component={Join}
    ... props />
</Router>

The problem is that I need some state variables of my App component (in app.js ) to be available in both Main and Join . 问题是我需要在MainJoin中都可以使用App组件(在app.js )的某些状态变量。 How do I achieve that with a router? 如何通过路由器实现?

App structure: 应用程序结构:

App
 - Join
 - Main
   - ...

You can use standard URL parameters. 您可以使用标准URL参数。 For example, to pass an ID: 例如,传递ID:

<Route path='join/:id' component={Join}/>

You'll need to use browserHistory: 您需要使用browserHistory:

browserHistory.push(`/join/${id}`);

Then use this.props.params.id on Join . 然后在Join上使用this.props.params.id

Here's a more in-depth explanations https://stackoverflow.com/a/32901866/48869 这是更深入的说明https://stackoverflow.com/a/32901866/48869

It depends how you are managing your state. 这取决于您如何管理状态。 if you use the Redux, you don't need to pass props in router, you can simple access redux in any component using connect, However if you don't use react then you can use the Redux router's hierarchy functionality 如果您使用Redux,则无需在路由器中传递道具,则可以使用connect轻松访问任何组件中的redux。但是,如果您不使用react,则可以使用Redux路由器的层次结构功能

Assume you have a route something like this 假设您有一条类似这样的路线

<route path="/student" component={studentHome}>
   <route path="/class" component={classHome} />
</route>

when you access the path 当您访问路径时

/student/class

React router will load the classHome component as children of StudentHome and you can simple pass props to classHome component. React路由器会将classHome组件作为StudentHome的子级加载,您可以将prop简单传递给classHome组件。

you student class Render method will be something like 您的学生班级的渲染方法将类似于

render(){
     const childrenWithProps = React.Children.map(this.props.children,
     (child) => React.cloneElement(child, {
       doSomething: this.doSomething
     })
    );

    return <div> some student component functionality
                <div>
                 {childrenWithProps}
                </div>
           </div>
}

more details about passing props to children: How to pass props to {this.props.children} 有关将道具传递给孩子的更多详细信息: 如何将道具传递给{this.props.children}

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

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