Reactjs - Route 中的`component` 与`render` [英] Reactjs - `component` vs `render` in Route
问题描述
我对 react-router-dom
(v4.3.1) 中 Route
的使用有两个疑问:
I have two doubts regarding usage of Route
from react-router-dom
(v4.3.1):
我们什么时候在
Route
中使用component
vsrender
:
<Route exact path='/u/:username/' component={ProfileComponent} />
<Route exact path='/u/:username/' render={() => <ProfileComponent />} />
username
?推荐答案
当你将一个组件传递给 component
属性时,组件会在 props.match 中获取路径参数.params
对象,即 props.match.params.username
在您的示例中:
When you pass a component to the component
prop, the component will get the path parameters in the props.match.params
object, i.e props.match.params.username
in your example:
class ProfileComponent extends React.Component {
render() {
return <div>{this.props.match.params.username}</div>;
}
}
当使用render
道具时,可以通过给render
函数的道具访问路径参数:
When using the render
prop, the path parameters can be accessed through the props given to the render
function:
<Route
exact
path='/u/:username/'
render={(props) =>
<ProfileComponent username={props.match.params.username}/>
}
/>
当您需要来自包含您的路由的组件的一些数据时,您通常使用 render
道具,因为 component
道具没有提供将额外道具传递给的真正方法组件.
You generally use the render
prop when you need some data from the component that contains your routes, since the component
prop gives no real way of passing in additional props to the component.
这篇关于Reactjs - Route 中的`component` 与`render`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!