简体   繁体   English

Reactjs - 路径中的`component` vs`grave`

[英]Reactjs - `component` vs `render` in Route

I have two doubts regarding usage of Route from react-router-dom ( v4.3.1 ): 关于使用来自react-router-domv4.3.1 )的Route ,我有两个疑问:

  1. When do we use component vs render in Route : 我们什么时候在Route使用component vs render

     <Route exact path='/u/:username/' component={ProfileComponent} /> <Route exact path='/u/:username/' render={() => <ProfileComponent />} /> 
  2. How to access the variable username in the URL in both ways? 如何以两种方式访问URL中的变量username

When you pass a component to the component prop, the component will get the path parameters in the props.match.params object, ie props.match.params.username in your example: 将组件传递给component prop时,组件将获取props.match.params对象中的路径参数,即props.match.params.username中的props.match.params.username

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

When using the render prop, the path parameters can be accessed through the props given to the render function: 使用render道具时,可以通过赋予render功能的道具访问路径参数:

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

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. 当您需要包含路径的组件中的某些数据时,通常使用render道具,因为component道具没有提供将额外道具传递给component真实方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM