【问题标题】:Render Props - React Route渲染道具 - 反应路线
【发布时间】:2019-02-03 20:02:01
【问题描述】:
const Home = () => <div>Home</div>

const App = () => {
  const someVariable = true;

  return (
    <Switch>
      {/* these are good */}
      <Route exact path='/' component={Home} />
      <Route
        path='/about'
        render={(props) => <About {...props}  />}
      />
    </Switch>
  )
}

const About = (props) => {
  return (
    <div>
      About   
    </div>
  )
} 

在代码示例中,在

<Route
        path='/about'
        render={(props) => <About {...props}  />}
      />

当 react 遇到 react-router 的 Route 组件的 render prop 时,它传递了什么 props?

鉴于https://reactjs.org/docs/render-props.html 的文档, 渲染道具是组件用来知道要渲染什么的函数道具, 是在 react-router 中的 Route 声明中传递的 props 传递的值

【问题讨论】:

    标签: reactjs react-router-v4


    【解决方案1】:

    props 由 Route 组件传递给 render prop 方法。你可以在 React Router 源代码中看到这一点。 Route 组件传递的 props 有match, location, history, staticContext。如果你想使用父组件中的 props,你定义了 render props 方法,那么你可以省略 props 参数。

    render={() =&gt; &lt;About {...props} /&gt;}

    然后你会从包含 Route 的组件中获取 props。

    您提供的示例没有多大意义,因为它复制了您仅在 Route 上使用“组件”道具所获得的行为。

    https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Route.js#L120

    【讨论】:

      【解决方案2】:

      在渲染方法中传递 props 时,您会获得 react router 默认 props,就像使用 component 而不是使用隐式获取所有这些 props 匹配、位置、历史记录和 staticContext 的渲染道具一样。并且您需要提供道具作为参数,否则它的渲染方法不会将道具传递给孩子,因为它会认为它未定义。

      这是 react 路由器中渲染道具的工作示例: https://codesandbox.io/s/72k8xz669j

      【讨论】:

        【解决方案3】:

        我们使用带有渲染道具的Route,

        <Route path = "/about" component={About} />
        

        或,

        <Route path = "/about" render= { (props) => <About {...props} } />
        

        第二个不同于第一个,因为在第二种情况下,About 组件可以访问通过 Route 传入的 props。

        比如说, 有一个 Profile 组件,

        <Route path="/admin/profile"
               render={ props => (
                      <Profile tabs= {"valuePassed"} {...props}  />  
                )}
         />
        

        现在在 Profile 组件中,我们可以访问所有的道具,

        this.props.tabs 在基于类的组件中提供“valuePasses”,而 props.tabs 用于功能组件。

        希望这会有所帮助。

        【讨论】:

        • 如果不添加{...props}会得到什么,我应该可以从this.props.tabs访问"valuePassed",不是吗??
        • @TayyabFerozi 是的,您可以访问 valuePassed,即作为“标签”道具传递。您无法访问的是调用渲染方法的其他道具,即(更具体地说-->) if {() } 有来自 的 {match: {...}, location: {...}, history: {...}} 等道具,然后如果您添加 {...props} 您可以访问这些在“管理员/个人资料”路线中也可以使用道具,否则您将只能访问 {tabs: {valuePassed}} 请参阅:levelup.gitconnected.com/… 希望这会有所帮助!
        猜你喜欢
        • 2020-04-05
        • 1970-01-01
        • 2019-03-02
        • 2021-01-29
        • 2022-01-22
        • 2021-10-31
        • 1970-01-01
        • 2023-01-02
        • 2018-06-16
        相关资源
        最近更新 更多