环境搭建
新建文件夹——React
进入文件夹.
$ cd React
构建环境
$ npm install -g create-react-app
$ create-react-app app //首字母不可以大写;名字不可以和父文件夹重名
$ cd app
$ npm start
使用react-route实现单页面应用路由
安装react-router
npm install --save react-router-dom
index.js代码
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
const BasicExample = () => (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</Router>
)
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const About = () => (
<div>
<h2>About</h2>
</div>
)
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
)
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
ReactDOM.render(<BasicExample/>, document.getElementById('main'));
提取布局组件
新建存储目录
新建/src/layouts目录用来存放布局组件,新建HomeLauout.js文件.
import React from 'react';
class HomeLayout extends React.Component {
render () {
const {title, children} = this.props;
return (
<div>
<header>
<h1>{title}</h1>
</header>
<main>
{children}
</main>
</div>
);
}
}
export default HomeLayout;
我们把每个页面中通用的部分提取到HomeLayout组件中,使用props.title来维护页面的标题和文本.
使用props.children渲染HomePage:
<HomeLayout title="Welcome">
<Link to="/user/list">List1</Link>
<br/>
<Link to="/user/add">List2</Link>
</HomeLayout>
重构页面
主页:
import HomeLayout from '../layouts/HomeLayout';
class Home extends React.Component {
render () {
return (
<HomeLayout title="Welcome">
<Link to="/user/list">List1</Link>
<br/>
<Link to="/user/add">List2</Link>
</HomeLayout>
);
}
}
UI框架
重现起步
项目结构
|- public
|- src
| |- components
| |- layouts
| |- redux
| |- routes
| |- styles
| |- utils
| |- views
|- index.js
笔记 Learning Notes Informal essay Environmental deployment
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!