首页 > 解决方案 > 使用高阶组件传递属性

问题描述

我对如何将位置对象传递给我的子函数感到困惑。它永远不会手动传入,并且似乎是自动传入的。

这可能是对到达路由器的增强吗?

我正在使用盖茨比。

高阶组件:

const PrivateRoute = ({ component: Component, location, ...rest }) => {
  return (
    <div>
      <h5>{location.pathname}</h5>
      <Component {...rest} />
    </div>
  )
}

使用地点:

  <Layout>
    <Router>
      <PrivateRoute path="/app/authorize" component={authContent} />
    </Router>
  </Layout>
)

子组件:

const authContent = ({ ...rest }) => (
  <div>
    <h1> {rest.name}</h1>
    <h1>Hello World</h1>
  </div>
)

标签: reactjsfunctional-programminggatsbyhigher-order-components

解决方案


实际上有 props 传递到路由的子组件中:

启用路由的历史记录。

匹配访问 URL 参数

和位置访问当前位置。

HOC 只是将这些作为附加道具添加到其渲染函数中。

希望有帮助。快乐编码。


推荐阅读