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