首页 文章

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

提问于
浏览
0

我想为我的应用使用网址路径 . 目前我只是在 app.js 中渲染一个 Main 组件:

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

(道具是一堆变量和功能)

我尝试使用react-router但我不明白如何向子组件发送道具 .

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

问题是我需要一些 App 组件的状态变量(在 app.js 中)在 MainJoin 中都可用 . 如何使用路由器实现这一目标?

应用结构:

App
 - Join
 - Main
   - ...

2 回答

  • 0

    这取决于你如何管理你的州 . 如果您使用Redux,您不需要在路由器中传递道具,您可以使用connect简单地访问任何组件中的redux,但是如果您不使用react,那么您可以使用Redux路由器的层次结构功能

    假设你有一条这样的路线

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

    当您访问路径时

    /student/class
    

    React路由器将classHome组件作为StudentHome的子项加载,您可以简单地将props传递给classHome组件 .

    你学生班的渲染方法会是这样的

    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>
    }
    

    关于向儿童传递道具的更多细节:How to pass props to

  • 0

    您可以使用标准URL参数 . 例如,要传递ID:

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

    你需要使用browserHistory:

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

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

    这是一个更深入的解释https://stackoverflow.com/a/32901866/48869

相关问题