Reactjs - `component` vs `render` in Route

我的梦境 提交于 2020-05-25 07:18:26

问题


I have two doubts regarding usage of Route from react-router-dom(v4.3.1):

  1. When do we use component vs render in Route:

    <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?

回答1:


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>;
  }
}

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}/>
  }
/>

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.



来源:https://stackoverflow.com/questions/51226685/reactjs-component-vs-render-in-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!