Reactjs - Route 中的`component` 与`render` [英] Reactjs - `component` vs `render` in Route

查看:20
本文介绍了Reactjs - Route 中的`component` 与`render`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  1. 我们什么时候在Route中使用component vs render:

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

  • 如何以两种方式访问​​URL中的变量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 - Route 中的`component` 与`render`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆