【问题标题】:Pass parameter to base layout route将参数传递给基本布局路线
【发布时间】:2017-01-18 19:15:49
【问题描述】:

我有一个使用 react-router 的 React 应用程序,但我正在为一个简单的功能而苦苦挣扎。我配置了以下路线:

<Router history={hashHistory}>
    <Route path="/" component={Layout}>
        <IndexRoute component={Home}></IndexRoute>
        <Route path="reports" name="reports" component={Reports}></Route>
        <Route path="help" name="help" component={Help}></Route>
    </Route>
</Router>

我的Layout 组件看起来像:

<div class="content-wrapper">
    <section class="content-header">
        <h1>{this.props.title}</h1>
    </section>
    <section class="content" ref="content">
        <div class="content-pad">
            {this.props.children}
        </div>
    </section>
</div>

我想知道如何将this.props.title 传递到这个Layout 组件中。

我尝试了以下方法:

1) 在路线中:

<Route path="reports" name="reports" component={Reports} title="Reports"></Route>

2) 在链接中:

<Link to="reports" title="Reports"><span><i class="fa fa-file"></i> Reports</span></Link>

3) 在带有查询参数的链接中:

<Link to={{ pathname: 'help', query: { title: 'Help' } }}><span><i class="fa fa-question"></i> Help</span></Link>

提前致谢!

【问题讨论】:

  • “title”属性应该来自哪里?它是动态的,还是从更高的组件传递的?或者你只是要手动传递它?似乎布局组件是顶级组件
  • 没错。布局是其他页面的“容器”。 title 属性将被传递给它,以便它可以呈现它正在呈现的页面的标题...

标签: reactjs react-router


【解决方案1】:

试试这个:

<Route path="/" title="my awesome title" component={Layout}>

在布局组件中:

<h1>{this.props.route.title}</h1>

【讨论】:

  • 它的工作..可以通过调用this.props.route.title来访问子组件中的标题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 2013-01-08
  • 1970-01-01
相关资源
最近更新 更多