学习react router总结
我是一只在学习前端知识的小白,最近在学习react。
首先引入了一个css样式(不在讨论范围内,忽略它),然后引入了react、reactDOM、react router。其中Router,Route,Link是暂时需要的组件
之后可以写三个组件,以A组件作为初始,并连接B组件,也许A里的Link可能会看不懂,不着急,向下看
使用ReactDOM.render将路由和组件联系在一起,并且让它们显示在页面中 <Router> <Route path="/" component={A}> <Route path="/b" component={B}/> <Route path="/c" component={C}/> </Route> </Router> 其A组件中需要加入{this.props.children},即显示子组件 3.子组件也可以写在Router中的routes属性中 let routes = <Route path="/" component={App}> <Route path="/repos" component={Repos}/> <Route path="/about" component={About}/> </Route>; <Router routes={routes} /> 4.path为可选属性(可以使用通配符),当没有写该属性的时候那么就会自动加载指定组件。 <IndexLink to="/" className="aaa"> 首页 </IndexLink> 在浏览器中打开文件
错误点1: 有些教程中并没有写Router的history属性,会出现错误,作为小白的我很难发现,所以要查阅其他大神的教程,或者直接提问(亲测有效),引入并加入属性 import { hashHistory,browserHistory,useRouterHistory} from 'react-router'; ReactDOM.render(( <Router history={hashHistory}> <Route path="/" component={A}> <Route path="b" component={B}> <Route path="c/:id" component={C} /> </Route> </Route> </Router> ),document.getElementById("aa"));
显示页面 当其他页面想要进入路由页面的时候,也可以使用history
从页面中我们可以看出,默认为A组件显示当前页,而没有加载B组件的内容,即A组件的this.props.children,这时是undefined。
这样,在首页中添加了D组件,在加载页面的时候会显示D组件,这样就可以在D组件中加入A组件的展示内容,有利于代码分离
以上面的例子为例,要访问C组件,则需要在地址栏输入http://192.168.0.101:8080/#/b... import {Router,Route,Link,IndexRoute,Redirect } from 'react-router'; ReactDOM.render(( <Router history={hashHistory}> <Route path="/" component={A}> <IndexRoute component={D} /> <Route path="b" component={B}> <Route path="/c/:id" component={C} /> <Redirect from="c/:id" to="/c/:id" /> </Route> </Route> </Router> ),document.getElementById("aa")); IndexRedirect 组件 则是用于访问根目录的时候,进行重定向 import {Router,Redirect,IndexRedirect } from 'react-router'; ReactDOM.render(( <Router history={hashHistory}> <Route path="/" component={A}> <IndexRoute component={D} /> <IndexRedirect to="/b" /> <Route path="b" component={B}> <Route path="/c/:id" component={C} /> <Redirect from="c/:id" to="/c/:id" /> </Route> </Route> </Router> ),document.getElementById("aa"));
function handleEnter(){ console.log("进入"); } function handleLeave(){ console.log("离开"); } ReactDOM.render(( <Router history={hashHistory}> <Route path="/" component={A}> <IndexRoute component={D} /> <IndexRedirect to="/b" /> <Route path="b" component={B}> <Route path="/c/:id" component={C} onEnter={handleEnter} onLeave={handleLeave} /> <Redirect from="c/:id" to="/c/:id" /> </Route> </Route> </Router> ),document.getElementById("aa")); 以上就是暂时对react router的学习总结 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |