通过HOC通过路线传递道具

时间:2019-04-03 09:57:05

标签: reactjs

我有这个路由器,应该具有布局的任何页面都用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>
  );
}

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

什么是AuthConsumer?

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

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

答案 2 :(得分:0)

我能够使它像这样工作:

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

答案 3 :(得分:0)

在定义通过状态和路线的情况下使用this.props.history.push。

this.props.history.push({ 路径名:“ / yourComponent”, 状态:{valueOrProps:valueWhichisassigning} })

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