本篇文章主要的講述了關於react搭建路由demo的詳情。還有關於專案中react-router的介紹,接下來我們一起來看這篇文章吧
關於react-router網上有很多介紹,在這裡必要嘮叨,其中在專案中react -router和react-router-dom功能是一樣的,引用一個就可以了。
1、react-router4.0以上的介紹。
發現文章寫得很好,這裡也必要嘮叨一次了。請閱:初探React Router 4.0
2、搭建的環境
a、使用create-react-app搭建
b、版本如下:
{ "name": "react-project-router", "version": "0.1.0", "private": true, "dependencies": { "react": "^16.4.1", "react-dom": "^16.4.1", "react-router-dom": "^4.3.1", "react-scripts": "1.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
3、檔案目錄結構
#4、index.js
import React from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter} from 'react-router-dom'; import './index.css'; import Root from './router/Routes'; import registerServiceWorker from './registerServiceWorker'; const mountNode = document.getElementById('root'); ReactDOM.render( <browserrouter> <root></root> </browserrouter>, mountNode ); registerServiceWorker();
5、App.js
/* App 应用总容器 */ import React, { Component } from 'react'; class App extends Component { render() { return <p>{this.props.children}</p>; } } export default App;
6、Router文件,路由配置
/* Root, Router 配置 */ import React from 'react'; import { Route, Switch, Redirect } from 'react-router-dom'; import App from './../App'; import Test from './../containers/Test'; import Home from './../containers/Home'; import Message from './../containers/Message'; const Root = () => ( <p> <switch> <route> ( <app> <switch> <route></route> <route></route> <route></route> <route></route> {/*路由不正确时,默认跳回home页面*/} <route> <redirect></redirect>} /> </route></switch> </app> )} /> </route></switch> </p> ); export default Root;
7、相關組件代碼(想看更多就到PHP中文網React參考手冊欄位中學習)
/* Home 主页 */ import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class Home extends Component { render() { return ( <p> {/*search,state可以自定义,获取方法:this.props.location.search,this.props.location.state*/} <link> 点击跳转到路由参数search,state使用 </p> ); } } export default Home; /* Test 主页 */ import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class Test extends Component { constructor (props) { super(props) } render() { return ( <p> </p><p>search:{this.props.location.search} </p> <p>state:{this.props.location.state.mold} </p> <p> this.props.history.goBack()}>返回上一页</p> <p> this.props.history.push('/message/12')}>message页面</p> ); } } export default Test; /* Message 主页 */ import React, { Component } from 'react'; class Message extends Component { constructor (props) { super(props) } render() { return ( <h3>Message{this.props.match.params.id}</h3> ); } } export default Message;
8、效果如下
本篇文章到這就結束了(想看更多就到PHP中文網React使用手冊欄位學習),有問題的可以在下方留言提問。
以上是React路由如何搭建demo? react建置路由demo的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!