编程语言
首页 > 编程语言> > javascript-Reactjs-`component` vs`render`在路线

javascript-Reactjs-`component` vs`render`在路线

作者:互联网

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

>我们何时在Route中使用组件vs渲染:

<Route exact path='/u/:username/' component={ProfileComponent} />
<Route exact path='/u/:username/' render={() => <ProfileComponent />} />

>如何通过两种方式访问​​URL中的变量用户名?

解决方法:

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

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

使用渲染道具时,可以通过提供给渲染函数的道具来访问路径参数:

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

当需要来自包含路线的组件中的一些数据时,通常会使用渲染道具,因为组件道具没有提供将其他道具传递到组件的真正方法.

标签:react-router-dom,reactjs,routes,javascript
来源: https://codeday.me/bug/20191108/2010054.html