前提
你需要准备好node.js版本不低于6.14.8 和 git
文章内容比较长(保姆级别教程),全是干货,请耐心看完
通过create-react-app脚手架搭建项目
1.第一步
- 打开文件夹,呼出cmd,输入搭建命令:
npx create-react-app 项目名称 --template typescript
注: 项目名称不可以出现大写字母
npx create-react-app test --template typescript
- 当你出现Happy hacking说明你下载成功了,vscode打开项目,可以看到顺利生成了react项目组件,后缀为tsx此时说明成功创建了react+typescript项目的雏形
2.第二步
- 进入项目更目录下,运行命令:
npm start
启动项目
npm start
配置路由
1.第一步
- npm下载路由命令:
npm i [email protected] [email protected] react-router-config @types/react-router-config @types/react-router-dom -S
npm i [email protected] [email protected] react-router-config @types/react-router-config @types/react-router-dom -S
2.第二步
- src目录下创建views文件夹,views内创建Home,Contact,About,Navbar四个tsx文件,其中Navbar用来控制路由,其他三个页面用来展示
- Home.tst:
import React, { Component } from "react";
export default class Home extends Component {
render() {
return (
<div className="home">
<div className="container">
<h3 className="center"> Home页面</h3>
<p>欢迎来到首页</p>
</div>
</div>
);
}
}
- Contact:
import React, { Component } from "react";
export default class Contact extends Component {
render() {
return (
<div className="contact">
<div className="container">
<h3 className="center"> Contact页面</h3>
<p>欢迎来到联系我们页面!</p>
</div>
</div>
);
}
}
- About:
import React, { Component } from "react";
export default class About extends Component {
render() {
return (
<div className="about">
<div className="container">
<h3 className="center"> About页面</h3>
<p>欢迎来到关于我们页面!</p>
</div>
</div>
);
}
}
- Navbar:
import React, { Component } from "react";
import { Link } from "react-router-dom";
export default class Navbar extends Component {
render() {
return (
<nav className="nav-wrapper">
<div className="list">
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='/about'>About</Link></li>
<li><Link to='/contact'>Contact</Link></li>
</ul>
</div>
</nav>
)
}
}
3.第三步
- src目录下创建routes文件夹,同时创建index.ts,使用RouteConfig对路由进行统一管理
- index.ts:
// 导入路由组件
import Home from '../views/Home'
import About from '../views/About'
import Contact from '../views/Contact'
// 导入路由管理工具
import {RouteConfig} from 'react-router-config'
const routes:RouteConfig = [
{
path:'/',
exact:true,
component:Home
},
{
path:'/about',
exact:true,
component:About
},
{
path:'/contact',
exact:true,
component:Contact
}
]
export default routes;
4.第四步
- App.tsx中引入Route,Navbar和路由管理工具
import React from "react";
// 引入路由导航栏
import Navbar from "./views/Navbar";
// 引入routes组件
import routes from "./routes";
// 引入包管理工具
import { renderRoutes, RouteConfig } from "react-router-config";
import "./App.css";
function App() {
return (
<div className="App">
<Navbar />
{/* 设置routes的类型为Ro