首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在React上下文中传递props和使用HOC

如何在React上下文中传递props和使用HOC
EN

Stack Overflow用户
提问于 2018-08-11 23:37:17
回答 1查看 698关注 0票数 0

我需要做这样的事情

const CreateActivity = (props) => (
<AuthUserContext.Consumer>
  {authUser =>
    <CreateActivityShow  email={authUser.email} {...props}/>
  }
</AuthUserContext.Consumer>

const authCondition = (authUser) => !!authUser;
export default withAuthorization(authCondition)(CreateActivity);

这样,我在createActivity上正确使用了我的HOC组件,但在CreateActivityShow this.props上,我只有this.props.email参数,没有this.props.match应该有的url参数……

我试过这种方式

  export default props =>  (
<AuthUserContext.Consumer>
  {authUser =>
    <CreateActivityShow {...props} email={authUser.email}/>
  }
</AuthUserContext.Consumer>
)

现在我有道具了,但我不知道如何在这里使用我的HOC

有没有办法同时做这两件事?

编辑:

我试过了

 export default withAuthorization(authCondition)( props =>  (
<AuthUserContext.Consumer>
  {authUser =>
    <CreateActivityShow {...props} email={authUser.email}/>
  }
</AuthUserContext.Consumer>
))

现在我又有了由withAuthorization包装的组件,但是现在不能传递道具,我不知道为什么……

这是我的

const withAuthorization = (authCondition) => (Component) => {
  class WithAuthorization extends React.Component {
  componentDidMount() {
    firebase.auth.onAuthStateChanged(authUser => {
      if (!authCondition(authUser)) {
        this.props.history.push(routes.SIGN_IN);
      }
    });
  }

render() {
  return (
    <AuthUserContext.Consumer>
      {authUser => authUser ? <Component /> : null}
    </AuthUserContext.Consumer>
  );
  }
}

return withRouter(WithAuthorization);
}

export default withAuthorization;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-12 00:30:24

是的,所以问题出在WithAuthorization组件中,你没有将HOC接收到的道具传递给呈现的组件。你会把它写成

const withAuthorization = (authCondition) => (Component) => {

    class WithAuthorization extends React.Component {
      componentDidMount() {
        firebase.auth.onAuthStateChanged(authUser => {
          if (!authCondition(authUser)) {
            this.props.history.push(routes.SIGN_IN);
          }
        });
      }

        render() {
          return (
            <AuthUserContext.Consumer>
              {authUser => authUser ? <Component {...this.props}/> : null}
            </AuthUserContext.Consumer>
          );
        }

    }

    return withRouter(WithAuthorization);
}

export default withAuthorization;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51801238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档