<Link>
// 默认会被渲染成一个 `<a>` 标签
<Link to="/about">About</Link>
类似Vue Router<router-link to="/about">about</router-link>
<Link>
组件支持用户在具有路由功能的应用中 (点击) 导航。 通过 to 属性指定目标地址,默认渲染成带有正确链接的 <a>
标签,比起写死的 <a href="...">
会好一些,理由如下:
1、无论是 HTML5 history 模式还是 hash 模式,它的表现行为一致,所以,当你要切换路由模式,或者在 IE9 降级使用 hash 模式,无须作任何变动。
2、在 HTML5 history 模式下,Link 会守卫点击事件,让浏览器不再重新加载页面。
to
类型: string | Location
pathname:表示链接到的路径的字符串。
search:查询参数的字符串。
hash:要输入网址的哈希,例如 #a-hash。
state:location预设的状态。
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true }
}}
/>
这些属性在路由组件中可以通过props.location属性获取。
<NavLink>
<Link>
的特殊版本,当它与当前URL匹配时,它将为呈现的元素添加样式属性。
<NavLink
to="/faq"
activeStyle={{
fontWeight: "bold",
color: "red"
}}
>
FAQs
</NavLink>
路由激活时高亮的效果
<Redirect>
渲染<Redirect>
将导航到新位置。 新位置将覆盖历史记录堆栈中的当前位置,就像服务器端重定向(HTTP 3xx)一样。
参数和Link组件类似。
<Route exact path="/">
{loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>
通常用于验证登录。
<Route>
它的最基本职责是在其路径与当前URL匹配时呈现一些UI。渲染路径匹配到的视图组件。
Route 渲染的方法
<Route component>
<Route render>
<Route children> function
建议使用<Route>
渲染某些内容的方法是使用子元素,但是,还有一些其他方法可用于使用<Route>
渲染内容。 提供这些主要是为了支持在引入钩子之前使用早期版本的路由构建的应用程序。
三种渲染方渲染出来的组件都一样,都有三个属性
match
location
history
使用component进行渲染组件
<Route path="/child" component={Child}></Route>
当您使用component时,路由会使用React.createElement从给定的组件中创建一个新的React元素。 这意味着,如果您向组件prop提供内联函数,则将在每个渲染中创建一个新组件。
// 这样写component={() => (<div>Child</div>)}无法复用之前的DOM了
<Route path="/child" component={() => (<div>Child</div>)}></Route>
这将导致现有组件的卸载和新组件的安装,而不仅仅是更新现有组件。 使用内联函数进行内联渲染时,请使用render或children属性(如下)。
render: func
<Route path="/child" render={() => (<div>Child</div>)}></Route>
这样可以方便地进行内联渲染和包装,而无需进行上述不必要的重新安装。
// 用于创建受保护的路由
const PrivateRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props =>
fakeAuth.isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect
to={{ pathname: "/login", state: { from: props.location } }}
/>
)
}
/>
);
};
警告:<Route component>
优先于 <Route render>
,因此请勿在同一<Route>
中同时使用两者。
children: func
children prop 与 render 类似,但是,无论路径与位置是否匹配,都会渲染子级。
function ListItemLink ({to, ...rest}) {
return (
<Route path={to} children={({match}) => {
console.log(match)
return (
<li className={match ? 'active': ''}>
<Link to={to} {...rest} >{to}</Link>
</li>
)
}}>
</Route>
)
}
上面实现的功能是路由菜单的选中效果,默认两个都会显示,如果把children换成render则只会显示匹配路径的那个。
根据具体的功能进行选中,现在你已经知道了他们之间的区别,默认通常使用 children elements 这种写法,
<Route path="/child">
<Child />
</Route>
您可以通过withRouter高阶组件访问location对象的属性和最接近的<Route>
匹配项。
function About(props) {
console.log(props, '这个是路由组件')
const handleClick = () => {
props.history.push('/')
}
return (
<div>
About
<button onClick={handleClick}>跳转首页</button>
</div>
)
}
const AboutWithRouter = withRouter(About);
<Route path="/about">
<AboutWithRouter />
</Route>
// 等同于 <Route path="/about" component={About}></Route>