react-router基本使用

xiaoxiao2021-02-28  36

react-router网站 http://reacttraining.cn/

学习react-router中遇到的问题

1.这段代码会存在啥问题呢?

render () { return ( <Router> <ul> <li> <Link to="/">首页</Link> </li> <li> <Link to="/about">关于</Link> </li> <li> <Link to="/themes">主题</Link> </li> </ul> <Route exact path="/" component = { Home } /> <Route path="/about" componnet={ About } /> <Route path="/themes" component={ Themes } /> </Router> ) }

报错如下:

A <Router> may have only one child element

意思就是说 一个Router仅仅有一个子组件。需要给Router里面加上一个div盒子。

因此我个人理解是Router只是个外壳,并不是一个容器。里面的div才是容器。

实现的效果:

代码如下:

import React,{ Component } from 'react'; import { BrowserRouter as Router, Route, Link, } from 'react-router-dom'; const Home = ()=> ( <div>首页</div> ) const About = ()=>( <div>关于</div> ) const Themes = ({ match })=>( <div> <h3>主题列表</h3> <ul> <li><Link to={ `${match.url}/rendering` }>渲染</Link></li> <li><Link to={ `${ match.url }/status`}>状态</Link></li> <li><Link to={ `${ match.url }/angular`}>Angular</Link></li> </ul> <Route path={ `${ match.url }/:id` } component={ Theme } /> <Route exact path={ `${ match.url }`} render={ ()=> { return <div>请选择一个主题</div> }} /> </div> ) const Theme = ({ match }) => ( <div> { `${match.params.id }` } </div> ) class BasicUse2 extends Component { constructor(props) { super(props); this.state = { } } render () { return ( <Router> <div> <ul> <li> <Link to="/">首页</Link> </li> <li> <Link to="/about">关于</Link> </li> <li> <Link to="/themes">主题</Link> </li> </ul> <Route exact path="/" component = { Home } /> <Route path="/about" componnet={ About } /> <Route path="/themes" component={ Themes } /> </div> </Router> ) } } export default BasicUse2;

需要理解的地方有:

(1)match 这里match是一个match对象,这也是作者为什么{ match } 这样写的原因。

(2) `${ match.url }/rendering` 完整的路径,匹配到这个路径,才是显示相应的组件。

(3)const Home = ()=( <div>首页</div>) 这里我用的是小括号,还可以这样写的,

    const Home = ()=> { return <div>首页</div> }

<Route>

<Route>也许是RR4最重要的组件了,它最基本的作用是:当页面的访问地址和Router的path相匹配时,就渲染出对应的UI界面。

<Route>自带3个render method 和3个props

render method 分别是:

<Route component >

<Route render>

<Route children>

props 分别是:

match

location

history

component

只有访问地址和路由匹配时,一个React Component才能被渲染。

render: func

此方法适用于内联渲染,而且不会出现重复装载的问题。

children

有时你只想知道访问地址是否匹配,然后改变下别的东西,而不仅仅是对应的页面。

path

需要匹配的路径

exact 

唯一匹配之后,展示对应的组件

strict:bool

对路径末尾斜杠的匹配。

<Link>

为你的应用提供声明式,无障碍导航。

to: string

作用: 跳转到制定路径。

使用场景: 如果是单纯的跳转就用字符串形式的路径。

<Link to="/about" />

to: object

作用:携带参数跳到制定的路径

转载请注明原文地址: https://www.6miu.com/read-2624138.html

最新回复(0)