Reactjs - 路线中的“组件"与“渲染" [英] 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 - 路线中的“组件"与“渲染"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!