React Router 4 的使用(2)

  • Route Rendering Props

对于给定的路由如何渲染组件,有三种选项:component、render、children。你可以查看 <Route> 的文档来获取更多的信息,但是在这我们关注 component 和 render ,因为这两个是经常用到的。

component 应该被用于当你有一组件(有状态的组件或者是一个函数组件),并且想要渲染它的时候

render ,它采用内联函数,只有当你必须将范围内的变量传递给要渲染的组件时,才应该使用它。

你不应该使用带有内联函数的组件支持来传递范围内的变量,因为您将得到不需要的组件卸载/重新配置。

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} extra={someVariable} />}
      />
      {/* do not do this */}
      <Route
        path='/contact'
        component={(props) => <Contact {...props} extra={someVariable} />}
      />  
    </Switch>
  )
}
  • Navigation

React Router 提供了一个<Link> 组件在你的应用程序中创建链接。无论在哪里渲染 <Link> ,一个锚点(<a>)将在应用程序的 HTML 中呈现

<Link to='/'>Home</Link>
// <a href='/'>Home</a>

<NavLink> 是 <Link> 的一个特殊类型,当其与当前位置匹配时它是活动的

// location = { pathname: '/react' }
<NavLink to='/react' activeClassName='hurray'>React</NavLink>
// <a href='/react' className='hurray'>React</a>

如果您想强制导航,您可以渲染一个<Redirect>。当一个<Redirect>呈现时,它将使用它来导航。

<Redirect to='/login'/>

先做个记录,挑个时间再来完善修改

原文地址:https://www.cnblogs.com/lan1974/p/8624932.html