(原)创建一个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

转载于:https://www.cnblogs.com/feng123/p/10271650.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值