将 props 传递给 react-router v4 中的路由器组件
Passing props to router component in react-router v4
例如:
import SomeComponent...
<Router>
<Route path='/' component={SomeComponent} />
</Router>
如何将某些内容传递给 SomeComponent
以便我可以通过 this.props.xxx
在组件中访问它?
试试这个:
<Router>
<Route path='/' component={(props) =>
(<SomeComponent value={this.state.value} {...props} )/>} />
</Router>
注意,如果要访问组件中的路由属性(例如组件代码中 this.props.history
中的匹配、位置或历史记录),则需要传递 ...props
。
更新:
出于性能原因,在这种情况下使用 render
可能更好,例如:
<Router>
<Route path='/' render={(props) =>
(<SomeComponent value={this.state.value} {...props} )/>} />
</Router>
根据react docs:
When you use component (instead of render or children) the
router uses React.createElement to create a new React element from the
given component. That means if you provide an inline function to the
component attribute, you would create a new component every render.
This results in the existing component unmounting and the new
component mounting instead of just updating the existing component.
When using an inline function for inline rendering, use the render or
the children prop (below).
例如:
import SomeComponent...
<Router>
<Route path='/' component={SomeComponent} />
</Router>
如何将某些内容传递给 SomeComponent
以便我可以通过 this.props.xxx
在组件中访问它?
试试这个:
<Router>
<Route path='/' component={(props) =>
(<SomeComponent value={this.state.value} {...props} )/>} />
</Router>
注意,如果要访问组件中的路由属性(例如组件代码中 this.props.history
中的匹配、位置或历史记录),则需要传递 ...props
。
更新:
出于性能原因,在这种情况下使用 render
可能更好,例如:
<Router>
<Route path='/' render={(props) =>
(<SomeComponent value={this.state.value} {...props} )/>} />
</Router>
根据react docs:
When you use component (instead of render or children) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component attribute, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).