1、快速安装create-react-app脚手架
npm isntall -g create-react-app
安装好了之后,看一下版本
create-react-app --version
创建js版本
npx create-react-app my-app
创建ts版本
npx create-react-app my-app --template typescript
使用antd
安装路由react-router-dom
js版本
yarn add react-router-dom
或者
npm install --save react-router-dom
ts 版本
npm i --save-dev @types/react-router-dom
修改App.tsx,添加路由
import React from 'react';
import { HashRouter, Route, Switch } from 'react-router-dom'
import './App.css';
import Home from '../src/pages/Home'
import Main from '../src/pages/Main'
// const Home = React.lazy(() => import('../src/pages/Home'))
const App: React.FC = () => {
return (
<HashRouter>
<Switch>
<Route exact path="/" component={Main}/>
<Route exact path="/home" component={Home}/>
</Switch>
</HashRouter>
);
}
export default App;
页面出现如下结果
改变路由 /home
懒加载的方式
import React from 'react';
import { HashRouter, Route, Switch } from 'react-router-dom'
import './App.css';
// import Home from '../src/pages/Home'
// import Main from '../src/pages/Main'
const Home = React.lazy(() => import('../src/pages/Home'))
const Main = React.lazy(() => import('../src/pages/Main'))
const App: React.FC = () => {
return (
<HashRouter>
{/* <Switch>
<Route exact path="/" component={Main}/>
<Route exact path="/home" component={Home}/>
</Switch> */}
{/* 懒加载的方式 需要使用 React.Suspense */}
<React.Suspense fallback={<div></div>}>
<Switch>
<Route exact path="/" component={Main}/>
<Route exact path="/home" component={Home}/>
</Switch>
</React.Suspense>
</HashRouter>
);
}
export default App;
引用*.module.less
yarn add less less-loader
使用命令打开react 脚手架的配置
npm run eject
找到其中的react-app-env.d.ts文件,添加如下代码
declare module '*.module.less' {
const classes: {
[key: string]: string;
};
export default classes;
}
如下图所示,便可在项目中使用*.module.less
请求接口
安装axios npm install axios
执行 GET 请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的请求也可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行 POST 请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});