(原)创建一个react项目,包含ant-design和router
1.安装和初始化
npm install -g create-react-app yarn
2.创建项目
create-react-app react-app
3.启动项目
npm start
地址:http://localhost:3000/
4.引入antd
现在从 yarn 或 npm 安装并引入 antd。
yarn add antd
npm install antd --save
修改 src/App.css
,在文件顶部引入 antd/dist/antd.css
。
@import '~antd/dist/antd.css'; .App { text-align: center; }
修改 src/App.js
,引入 antd 的按钮组件。
import React, { Component } from 'react'; import Button from 'antd/lib/button'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <Button type="primary">Button</Button> </div> ); } } export default App;
页面显示如下
5.添加router
安装router
npm install react-router react-router-dom --save
目录结构
创建components文件夹,并且在其中新建 home.jsx和about.jsx(路由到子页面)
home.jsx
import React from 'react' import { Link } from 'react-router-dom' const Home = () => ( <div> <p>路由首页</p> <Link to="/about">关于我们</Link> </div> ) export default Home
about.jsx
import React from 'react' import { Link } from 'react-router-dom' const About = () => ( <div> <p>这张页面是关于我们的页面</p> <Link to="/home">返回首页</Link> </div> ) export default About
创建routes
文件夹,并且在其中新建 index.jsx
页面(路由页面)
import React from 'react' import { Route, Redirect } from 'react-router' import { HashRouter, Switch } from 'react-router-dom' import Home from '../components/home' import About from '../components/about' const Routes = () => ( <HashRouter> <div> <Route exact path="/" render={() => <Redirect to="/home" />} /> <Switch> <Route path="/home" component={Home} /> <Route path="/about" component={About} /> </Switch> </div> </HashRouter> ) const App = () => ( <Routes /> ) export default App
index.js修改路由指向
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; // import App from './App'; import App from './routes/index' import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
页面显示
Q&A
npm start 包错误
npm i react-scripts
项目代码见github