如何通过HOC调用传递道具

时间:2018-10-02 12:35:39

标签: reactjs

所以这是我的问题。我在我的React Router中使用HOC。看起来像这样:

    <BrowserRouter>
      <div className="main__container">
        <Route exact path="/" component={authHOC(MainView)} />
        <Route path="/article" component={authHOC(Article)} />
        <Route path="/apps" component={authHOC(AppList)} />
      </div>
    </BrowserRouter>

现在,我想将一些道具传递给包装好的组件。我想要这样的东西:

component={authHOC(Article({ header: true })}

以便将道具传递给我的组件。以上将无法正常工作。有办法通过吗?

我的HOC组件如下所示:

export default function(ProtectedComponent, addProps) {
  return class LoginPage extends Component {

    checkUserAuth = async() => {
      const token = await api.getAuthToken();
      this.setState({ isUserLoggedIn: !!token, loading: false });
    };

    redirectToAuth = () => <Redirect to="/login" />;

    render() {
      const { isUserLoggedIn, loading } = this.state;

      if(!loading) {
        return isUserLoggedIn ? (
          <ProtectedComponent {...this.props} {...addProps} />
        ) : this.redirectToAuth();
      }

      return null;
    }
  };
}

1 个答案:

答案 0 :(得分:2)

除非像this is done on purpose,否则不应像Article({ header: true })那样直接调用组件。

高阶组件可以接受一个组件以及包装的组件中使用的其他参数,如the guide所示,例如:

<Route exact path="/" component={authHOC(MainView, { header: true })} />

const authHOC = (Comp, props) => <Comp {...props}/>;

如果authHOC是无法修改的第三方HOC,则应为其提供增强的组件:

<Route exact path="/" component={
  authHOC(props => <MainView {...props} header={true} />)
} />
相关问题