react路由案例(非常适合入门)
前面已经已经讲过一次路由 稍微有些复杂 考虑到有些同学刚接触到 我准备了一个简单的demo 就当自己也顺便复习一下
data.js
const data = [
{
name: 'Tacos',
description: 'A taco (/ˈtækoʊ/ or /ˈtɑːkoʊ/) is a traditional Mexican dish composed of a corn or wheat tortilla folded or rolled around a filling. A taco can be made with a variety of fillings, including beef, pork, chicken, seafood, vegetables and cheese, allowing for great versatility and variety. A taco is generally eaten without utensils and is often accompanied by garnishes such as salsa, avocado or guacamole, cilantro (coriander), tomatoes, minced meat, onions and lettuce.',
items: [
{ name: 'Carne Asada', price: 7 },
{ name: 'Pollo', price: 6 },
{ name: 'Carnitas', price: 6 }
]
},
{
name: 'Burgers',
description: 'A hamburger (also called a beef burger, hamburger sandwich, burger or hamburg) is a sandwich consisting of one or more cooked patties of ground meat, usually beef, placed inside a sliced bun. Hamburgers are often served with lettuce, bacon, tomato, onion, pickles, cheese and condiments such as mustard, mayonnaise, ketchup, relish, and green chile.',
items: [
{ name: 'Buffalo Bleu', price: 8 },
{ name: 'Bacon', price: 8 },
{ name: 'Mushroom and Swiss', price: 6 }
]
},
{
name: 'Drinks',
description: 'Drinks, or beverages, are liquids intended for human consumption. In addition to basic needs, beverages form part of the culture of human society. Although all beverages, including juice, soft drinks, and carbonated drinks, have some form of water in them, water itself is often not classified as a beverage, and the word beverage has been recurrently defined as not referring to water.',
items: [
{ name: 'Lemonade', price: 3 },
{ name: 'Root Beer', price: 4 },
{ name: 'Iron Port', price: 5 }
]
}
] const dataMap = data.reduce((map,category) => //重点看这里 在干嘛 对es6很有帮助哟
{
category.itemMap =
category.items.reduce((itemMap,item)=>{
itemMap[item.name] = item;
return itemMap
},{})
map[category.name] = category;
return map
},
{}
) exports.getAll = function () {
return data
} exports.lookupCategory = function (name) {
return dataMap[name]
} exports.lookupItem = function (category, item) {
return dataMap[category].itemsMap[item]
}
app.js
import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link } from 'react-router' import withExampleBasename from '../withExampleBasename'
import data from './data' import './app.css' const category = ({children,params})=>{
const category = data.lookupCategory(params.category) return (
<div>
<h1>{category.name}</h1>
{children || (
<p>{category.description}</p>
)}
</div>
)
} const CategorySidebar = ({ params }) => {
const category = data.lookupCategory(params.category) return (
<div>
<Link to="/">◀︎ Back</Link> // "/" 根目录 到app组件 app包含什么 往下看
<h2>{category.name} Items</h2>
<ul>
{category.items.map((item, index) => (
<li key={index}>
<Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link> //见下面的route
</li>
))}
</ul>
</div>
)
} const Item = ({ params: { category, item } }) => {
const menuItem = data.lookupItem(category, item) return (
<div>
<h1>{menuItem.name}</h1>
<p>${menuItem.price}</p>
</div>
)
} const Index = () => (
<div>
<h1>Sidebar</h1>
<p>
Routes can have multiple components, so that all portions of your UI
can participate in the routing.
</p>
</div>
) const IndexSidebar = () => (
<div>
<h2>Categories</h2>
<ul>
{data.getAll().map((category, index) => (
<li key={index}>
<Link to={`/category/${category.name}`}>{category.name}</Link>
</li>
))}
</ul>
</div>
) const App = ({ content, sidebar }) => (
<div>
<div className="Sidebar">
{sidebar || <IndexSidebar />}
</div>
<div className="Content">
{content || <Index />}
</div>
</div>
) render((
<Router history={withExampleBasename(browserHistory, __dirname)}>
<Route path="/" component={App}>
<Route path="category/:category" components={{ content: Category, sidebar: CategorySidebar }}> // 一级
<Route path=":item" component={Item} /> //二级
</Route>
</Route>
</Router>
), document.getElementById('example'))
看懂了吧 很简单吧
我们再来看一个例子
import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link } from 'react-router' import withExampleBasename from '../withExampleBasename' const User = ({ params: { userID }, location: { query } }) => {
let age = query && query.showAge ? '33' : '' return (
<div className="User">
<h1>User id: {userID}</h1>
{age}
</div>
)
} const App = ({ children }) => (
<div>
<ul>
<li><Link to="/user/bob" activeClassName="active">Bob</Link></li>
<li><Link to={{ pathname: '/user/bob', query: { showAge: true } }} activeClassName="active">Bob With Query Params</Link></li>
<li><Link to="/user/sally" activeClassName="active">Sally</Link></li>
</ul>
{children}
</div>
) render((
<Router history={withExampleBasename(browserHistory, __dirname)}>
<Route path="/" component={App}>
<Route path="user/:userID" component={User} />
</Route>
</Router>
), document.getElementById('example'))
简单吧 找到自信了吗 。。。
最后看一个复杂一点的 当做巩固吧
一个一个来
import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, IndexRoute, Link } from 'react-router' import withExampleBasename from '../withExampleBasename' const PICTURES = [
{ id: 0, src: 'http://placekitten.com/601/601' },
{ id: 1, src: 'http://placekitten.com/610/610' },
{ id: 2, src: 'http://placekitten.com/620/620' }
] const Modal = React.createClass({
styles: {
position: 'fixed',
top: '20%',
right: '20%',
bottom: '20%',
left: '20%',
padding: 20,
boxShadow: '0px 0px 150px 130px rgba(0, 0, 0, 0.5)',
overflow: 'auto',
background: '#fff'
}, render() {
return (
<div style={this.styles}>
<p><Link to={this.props.returnTo}>Back</Link></p> //这里是要返回当前属性的地址
{this.props.children}
</div>
)
}
})
const App = React.createClass({ componentWillReceiveProps(nextProps) { //组件改变时 就是路由切换时
// if we changed routes...
if ((
nextProps.location.key !== this.props.location.key && //经过上面的讲解这里的location.key和state 懂吧
nextProps.location.state &&
nextProps.location.state.modal
)) {
// save the old children (just like animation)
this.previousChildren = this.props.children
}
}, render() {
let { location } = this.props let isModal = (
location.state &&
location.state.modal &&
this.previousChildren
) return (
<div>
<h1>Pinterest Style Routes</h1> <div>
{isModal ?
this.previousChildren :
this.props.children
} {isModal && (
<Modal isOpen={true} returnTo={location.state.returnTo}> // 这里是往回跳转
{this.props.children} //大家要问this,props.children 是指的什么
</Modal>
)}
</div>
</div>
)
}
})
index-route 当app没有定义时 被包含进去
const Index = React.createClass({
render() {
return (
<div>
<p>
The url `/pictures/:id` can be rendered anywhere in the app as a modal.
Simply put `modal: true` in the location descriptor of the `to` prop.
</p> <p>
Click on an item and see its rendered as a modal, then copy/paste the
url into a different browser window (with a different session, like
Chrome -> Firefox), and see that the image does not render inside the
overlay. One URL, two session dependent screens :D
</p> <div>
{PICTURES.map(picture => (
<Link
key={picture.id}
to={{
pathname: `/pictures/${picture.id}`,
state: { modal: true, returnTo: this.props.location.pathname }
}}
>
<img style={{ margin: 10 }} src={picture.src} height="100" />
</Link>
))}
</div> <p><Link to="/some/123/deep/456/route">Go to some deep route</Link></p> </div>
)
}
})
大家如果还是不很懂 可以看一下index-route 举个例子
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, hashHistory, IndexRoute } from 'react-router'
import App from './modules/App'
import About from './modules/About'
import Repos from './modules/Repos'
import Repo from './modules/Repo'
import Home from './modules/Home' render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={Repo}/>
</Route>
<Route path="/about" component={About}/>
</Route>
</Router>
), document.getElementById('app'))
看下app.js
import React from 'react'
import NavLink from './NavLink' export default React.createClass({
render() {
return (
<div>
<h1>React Router Tutorial</h1>
<ul role="nav">
<li><NavLink to="/about">About</NavLink></li>
<li><NavLink to="/repos">Repos</NavLink></li>
</ul>
{this.props.children} //如果一开始访问 根目录/ 其他的字组件还没包含进去 那么。。。 看下面
</div>
)
}
})
home.js
import React from 'react' export default React.createClass({
render() {
return <div>Home</div> //知道了吧 刚才进去 被包含进去的就是home组件 当进行路由跳转的时候
}
})
navLink.js
// modules/NavLink.js
import React from 'react'
import { Link } from 'react-router' export default React.createClass({
render() {
return <Link {...this.props} activeClassName="active"/>
}
})
repo.js
import React from 'react' export default React.createClass({
render() {
return (
<div>
<h2>{this.props.params.repoName}</h2>
</div>
)
}
})
repos.js
import React from 'react'
import NavLink from './NavLink' export default React.createClass({
render() {
return (
<div>
<h2>Repos</h2>
<ul>
<li><NavLink to="/repos/reactjs/react-router">React Router</NavLink></li>
<li><NavLink to="/repos/facebook/react">React</NavLink></li>
</ul>
{this.props.children} //repos肯定有子路由
</div>
)
}
})
无关紧要的about.js
import React from 'react' export default React.createClass({
render() {
return <div>About</div>
}
})
最重要的index.js
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, hashHistory, IndexRoute } from 'react-router'
import App from './modules/App'
import About from './modules/About'
import Repos from './modules/Repos'
import Repo from './modules/Repo'
import Home from './modules/Home' render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={Repo}/>
</Route>
<Route path="/about" component={About}/>
</Route>
</Router>
), document.getElementById('app'))
我们来整理一下
1.进入根目录/ 渲染app 下面有home 和 repos(下面又有repo)
2.根据指定路径到不同组件 上面代码中,用户访问/repos
时,会先加载App
组件,然后在它的内部再加载Repos
组件。
今天就这么多 这些基础的东西还是很重要的 话说我最近还真是忙呀
一个屁点大的公司,就我一个前端,还tm什么都要会,静态页面lz一个人些,还要做交互的特效,坑爹的事各种响应式,还非要什么flex布局。。。这还没完呀
而且搞完了lz还要去用redux开发后台页面,现在小公司没一个不坑的,借口都是培养成全站式程序员,但又没实际的培训的技术指导,总监和pm什么的都在家
遥控指挥,你觉得这不是笑话么。。。笑话归笑话,又要开始烧脑了
react路由案例(非常适合入门)的更多相关文章
- Laravel初级教程浅显易懂适合入门
整理了一些Laravel初级教程,浅显易懂,特适合入门,留给刚学习laravel想快速上手有需要的朋友 最适合入门的laravel初级教程(一)序言 最适合入门的laravel初级教程(二)安装使用 ...
- Vue-CLI项目路由案例汇总
0901自我总结 Vue-CLI项目路由案例汇总 router.js import Vue from 'vue' import Router from 'vue-router' import Cour ...
- react第十二单元(react路由-使用react-router-dom-认识相关的组件以及组件属性)
第十二单元(react路由-使用react-router-dom-认识相关的组件以及组件属性) #课程目标 理解路由的原理及应运 理解react-router-dom以及内置的一些组件 合理应用内置组 ...
- react第十五单元(react路由的封装,以及路由数据的提取)
第十五单元(react路由的封装,以及路由数据的提取) #课程目标 熟悉react路由组件及路由传参,封装路由组件能够处理路由表 对多级路由能够实现封装通用路由传递逻辑,实现多级路由的递归传参 对复杂 ...
- react第十四单元(react路由-react路由的跳转以及路由信息)
第十四单元(react路由-react路由的跳转以及路由信息) #课程目标 理解前端单页面应用与多页面应用的优缺点 理解react路由是前端单页面应用的核心 会使用react路由配置前端单页面应用框架 ...
- react第十三单元(react路由-react路由的跳转以及路由信息) #课程目标
第十三单元(react路由-react路由的跳转以及路由信息) #课程目标 熟悉掌握路由的配置 熟悉掌握跳转路由的方式 熟悉掌握路由跳转传参的方式 可以根据对其的理解封装一个类似Vue的router- ...
- 适合入门自学服装裁剪滴书(更新ing)
[♣]适合入门自学服装裁剪滴书(更新ing) [♣]适合入门自学服装裁剪滴书(更新ing) 适合入门自学服装裁剪滴书(更新ing) 来自: 裁缝阿普(不为良匠,便为良医.) 2014-04-06 23 ...
- Easyui + asp.net mvc + sqlite 开发教程(录屏)适合入门
Easyui + asp.net mvc + sqlite 开发教程(录屏)适合入门 第一节: 前言(技术简介) EasyUI 是一套 js的前端框架 利用它可以快速的开发出好看的 前端系统 web ...
- React Native 系列(一) -- JS入门知识
前言 本系列是基于React Native版本号0.44.3写的,最初学习React Native的时候,完全没有接触过React和JS,本文的目的是为了给那些JS和React小白提供一个快速入门,让 ...
随机推荐
- [.net 面向对象编程基础] (13) 面向对象三大特性——多态
[.net 面向对象编程基础] (13) 面向对象三大特性——多态 前面两节,我们了解了面向对象的的封装和继承特性,面向对象还有一大特性就是多态.比起前面的封装和继承,多态这个概念不是那么好理解.我们 ...
- HTML5 history API实践
一.history API知识点总结 在HTML4中,我们已经可以使用window.history对象来控制历史记录的跳转,可以使用的方法包括: history.forward();//在历史记录中前 ...
- java提高篇(三)-----java的四舍五入
Java小事非小事!!!!!!!!!!!! 四舍五入是我们小学的数学问题,这个问题对于我们程序猿来说就类似于1到10的加减乘除那么简单了.在讲解之间我们先看如下一个经典的案例: public stat ...
- html表格相关
<html> <head> <style type="text/css"> thead {color:green} tbody {color:b ...
- jQuery基础之选择器
摘自:http://www.cnblogs.com/webmoon/p/3169360.html jQuery基础之选择器 选择器是jQuery的根基,在jQuery中,对事件处理.遍历DOM和Aja ...
- [ZigBee] 4、ZigBee基础实验——中断
前言 上一篇介绍了CC2530的IO的基础知识,并用LED的控制来展示如何配置并控制GPIO的输出,用KEY状态的读取实验来展示如何读取GPIO的状态.从上一节的KEY状态读取的代码看出是采用轮训方式 ...
- 翻译:AKKA笔记 - Actor消息 -1(一)
从第一篇Akka笔记的介绍中,我们是从很高的高度去观察Akka工具箱中的Actors.在这篇笔记的第二篇,我们会看一下Actors中的消息部分.而且延续上一次的例子,我们还会使用同样的学生与老师的例子 ...
- 说说设计模式~桥梁模式(Bridge)
返回目录 在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,那么如何应对这种“多维度的变化”?如何利用面向对象的技术来使得该类型能够轻松的沿着多个方向进行变化,而又不引入额外的复杂度? ...
- 程序员藏经阁 Linux兵书
程序员藏经阁 Linux兵书 刘丽霞 杨宇 编 ISBN 978-7-121-21992-4 2014年1月出版 定价:79.00元 536页 16开 内容提要 <Linux兵书>由浅 ...
- C#设计模式-工厂模式
引入人.工厂.和斧子的问题 原始社会时,劳动社会基本没有分工,需要斧子的人(调用者)只好自己去磨一把斧子,每个人拥有自己的斧子,如果把大家的石斧改为铁斧,需要每个人都要学会磨铁斧的本领,工作效率极低. ...