查看: 4|回复: 0

React项目使用React-Router

[复制链接]

4

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2012-5-21
发表于 2019-12-11 14:00:00 | 显示全部楼层 |阅读模式

⒈初始化React项目(略)

  请参考  初始化一个React项目(TypeScript环境)

⒉集成React-Router

  在React世界里,公认最好用的路由是React-Router。那我们直接来集成它吧。

yarn add react-router history
#如果是type环境
yarn add react-router @types/react-router history @types/history

⒊配置React-Router

  在src中新建一个文件叫Router.js(如果是type环境则名称为Router.tsx):

cd src
cd.>Router.js #如果是type环境 cd.>Router.tsx

  代码如下:

import {createBrowserHistory} from 'history';
import React from 'react';
import {Route,Router} from 'react-router';
import App from './App';
import Edit from './Edit';

const history = createBrowserHistory()

export default () => (
  <Router history={history}>
    <>
      <Route exact path="/" component={App}/>
    </>
  </Router>
)

  然后修改index.js(type环境为index.tsx)文件,将读取的组件修改为Router:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
// import App from './App';
import * as serviceWorker from './serviceWorker';
import Router from './Router';

// ReactDOM.render(<App />, document.getElementById('root'));
ReactDOM.render(<Router/>,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: https://bit.ly/CRA-PWA
serviceWorker.unregister();

  刷新一下页面,运行正常

  那我们再添加一个页面Edit.js(type环境为Edit.tsx),并为它配好路由:

Edit.js
import React from 'react';

export default () => (
  <div>Edit</div>
)
Router.js
import {createBrowserHistory} from 'history';
import React from 'react';
import {Route,Router} from 'react-router';
import App from './App';
import Edit from './Edit';

const history = createBrowserHistory()

export default () => (
  <Router history={history}>
    <>
      <Route exact path="/" component={App}/>
      <Route path="/edit" component={Edit}/>
    </>
  </Router>
)


来源:https://www.cnblogs.com/fanqisoft/p/12022163.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部