Reactjs - 路由中的"组件"与"渲染"



我对react-router-dom(v4.3.1)中Route的使用有两个疑问:

  1. 我们什么时候在Route中使用componentrender

    <Route exact path='/u/:username/' component={ProfileComponent} />
    <Route exact path='/u/:username/' render={() => <ProfileComponent />} />
    
  2. 如何以两种方式访问URL中的变量username

当您将组件传递给componentprop 时,该组件将获取props.match.params对象中的路径参数,即在您的示例中props.match.params.username

class ProfileComponent extends React.Component {
render() {
return <div>{this.props.match.params.username}</div>;
}
}

使用renderprop 时,可以通过提供给render函数的 props 访问路径参数:

<Route
exact
path='/u/:username/'
render={(props) => 
<ProfileComponent username={props.match.params.username}/>
}
/>

当您需要包含路由的组件中的一些数据时,您通常会使用renderprop,因为componentprop 没有提供将其他 props 传递给组件的真正方法。

最新更新