【问题标题】:How to specify a parameter of a component in react-router?如何在 react-router 中指定组件的参数?
【发布时间】:2017-02-19 16:07:00
【问题描述】:

我最近在使用 React-router,发现它不是那么直观。 这是我的情况。我定义了一个无状态的 React 组件“MainLayout”,它有两个参数,包括“headerBar”组件和“children”组件。

mainlayout.js:

const MainLayout = ({children,headerBar})=>{
  return (
    <div className="app">
      {headerBar}
      <main>
      {children}
      </main>
    </div>
  );
}
export default MainLayout;

我的路线是这样的:

routes.js:

export default (
  <Router history={browserHistory}>
    <Route component={MainLayout}> -----> how to specify "headerBar"
      <Route path="/" component={Home} />

      <Route path="widgets">
        <Route component={SearchLayout}>
          <IndexRoute component={WidgetList} />
        </Route>
      </Route>

    </Route>
  </Router>
);

在这种情况下,如何在“MainLayout”的Route中指定“headerBar”?

谢谢

德里克

【问题讨论】:

  • 你使用任何一种状态容器吗? (Redux,通量...)
  • @shota 不,我没有使用任何容器。

标签: reactjs react-router


【解决方案1】:

使用 react router,你可以在子路由中声明多个组件。此功能称为Named Components

这里也处理过这个话题:Using React-Router with a layout page or multiple components per page

你应该这样写:

<Route path="/" components={{body: Home, header: HeaderBar}} />

const MainLayout = ({body,header})=>{
  return (
    <div className="app">
      {header}
      <main>
      {body}
      </main>
    </div>
  );
}

问候

【讨论】:

  • 我试过了,但它无法工作并得到“warning.js:36Warning:失败的道具类型:无效的道具component提供给Route。”
  • 你使用的是哪个版本的 react 路由器?
  • 它是 2.8.1 谢谢。
  • 好的,我认为component 中的&lt;Route path="/" components={body: Home, header: HeaderBar} /&gt; 不需要's'。我更新我的帖子
猜你喜欢
  • 2016-09-14
  • 2022-11-29
  • 2017-10-31
  • 2020-04-14
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
  • 2022-07-20
  • 2017-10-24
相关资源
最近更新 更多