通过HOC途径传递道具

问题描述 投票:0回答:4

我有这个路由器,任何应该有布局的页面都包含在withLayout HOC中。

我需要传递给用户上下文的一些页面,我该如何添加user道具?

const withLayout = () => Component => props => (
  <div css={pageWrap}>
    <Header user={props.user} />
    <Component {...props} />
  </div>
);

export default function Router() {
  return (
    <AuthConsumer>
      {({ user }) => (
        <Switch>
          <Route exact path="/" component={withLayout()(Home, { user })} />
          <Route exact path="/page1" component={withLayout()(Page1)} />
          <Route exact path="/page2" component={withLayout()(Page2)} />
        </Switch>
      )}
    </AuthConsumer>
  );
}
reactjs
4个回答
2
投票

我认为你的withLayout有问题。它应该是:

const withLayout = () => (Component, props = {}) => (
  <div css={pageWrap}>
    <Header user={props.user} />
    <Component {...props} />
  </div>
);

0
投票

什么是AuthConsumer?

您可以在页面组件中使用contextType = AuthContext。 [from]

class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}

0
投票

我能够像这样工作:

<Route exact path="/" render={props => withLayout()(Home)({ ...props, user })} />

0
投票

使用this.props.history.push并传递定义的状态和路由。

this.props.history.push({pathname:'/ yourComponent',State:{valueOrProps:valueWhichisassigning}})

并在this.props.location.state.valueOrProps的下一个组件访问值中。

© www.soinside.com 2019 - 2024. All rights reserved.