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

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

问题描述

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

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


  1. 何时使用组件 vs 渲染中的路线

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


  • 如何访问变量用户名 URL 有两种方式吗?

  • How to access the variable username in the URL in both ways?

  • 推荐答案

    当您传递组件时到 component 道具,该组件将在 props.match.params 对象中获取路径参数,即<$在您的示例中,c $ c> 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 道具时需要包含包含您的路线的组件中的一些数据,因为组件道具没有提供将其他道具传递给组件的真正方法。

    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` vs`render`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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