[英]Wrap a React route render function in a HOC
I am using React-Router 4 to create some routes. 我正在使用React-Router 4来创建一些路由。 (It uses the PrivateRoute
component from the official docs but that's not relevant to this question.) (它使用官方文档中的PrivateRoute
组件,但这与此问题无关。)
<HashRouter>
<Switch>
<PrivateRoute exact path='/' component={Wrapper(Home)} />
<Route exact path='/login' render={(props) => <Login authenticate={this.authenticate} {...props} />} />
<PrivateRoute exact path='/clients' component={Wrapper(Clients)} />
</Switch>
</HashRouter>
As you can see the Home
and Clients
components are wrapped in an HOC . 如您所见, Home
和Clients
组件包含在HOC中 。 For the moment this does nothing: 目前这没有任何作用:
const Wrapper = (Page) => {
return (props) => (
<div className="page">
<p>This should be on every page</p>
<Page {...props} />
</div>
);
}
This works fine. 这很好用。 What I can't figure out is how to wrap the Login
route in the same HOC. 我无法弄清楚的是如何将Login
路由包装在同一个HOC中。 I've tried 我试过了
<Route exact path='/login' render={(props) => Wrapper(<Login authenticate={this.authenticate} {...props} />)} />
But this returns the error: 但是这会返回错误:
Route.render(): A valid React element (or null) must be returned. Route.render():必须返回有效的React元素(或null)。
Can you try doing it like that: 你能尝试这样做吗:
<Route exact path='/login' render={(props) => Wrapper(Login)({...props, authenticate: this.authenticate})} />
Because now Wrapper HOC is returning a function, but the react element is expected. 因为现在Wrapper HOC正在返回一个函数,但是反应元素是预期的。 To get the react element we'll need to call this function with the needed props and that seems like a good place to add that extra prop this.authenticate
. 要获得react元素,我们需要使用所需的道具来调用此函数,这似乎是添加额外道具this.authenticate
的好地方。
Here's a quick snippet I made: https://stackblitz.com/edit/react-zestnq 这是我制作的快速片段: https : //stackblitz.com/edit/react-zestnq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.