react-router-dom ╰半橙微兮° 2023-06-05 08:50 6阅读 0赞 1.安装 npm install react-router-dom --save-dev //这里可以使用cnpm代替npm命令 2. 基本操作 home.js import React from 'react'; export default class Home extends React.Component { render() { return ( <div> <a>去detail</a> </div> ) } } detail.js import React from 'react'; export default class Home extends React.Component { render() { return ( <div> <a>回到home</a> </div> ) } } Router.js import React from 'react'; import {HashRouter, Route, Switch} from 'react-router-dom'; import Home from '../home'; import Detail from '../detail'; const BasicRoute = () => ( <HashRouter> <Switch> <Route exact path="/" component={Home}/> <Route exact path="/detail" component={Detail}/> </Switch> </HashRouter> ); export default BasicRoute; index.js import React from 'react'; import ReactDOM from 'react-dom'; import Router from './router/router'; ReactDOM.render( <Router/>, document.getElementById('root') ); 3.通过a标签跳转 home.js import React from 'react'; export default class Home extends React.Component { render() { return ( <div> <a href='#/detail'>去detail</a> </div> ) } } detail.js import React from 'react'; export default class Home extends React.Component { render() { return ( <div> <a href='#/'>回到home</a> </div> ) } } 4. 通过函数跳转 1.首先在router.js中添加 import {HashRouter, Route, Switch, hashHistory} from 'react-router-dom'; <HashRouter history={hashHistory}> 2. 在home.js import React from 'react'; export default class Home extends React.Component { constructor(props) { super(props); } render() { return ( <div> <a href='#/detail'>去detail</a> <button onClick={() => this.props.history.push('detail')}>通过函数跳转</button> </div> ) } } 在a标签下面添加一个按钮并加上onClick事件,通过this.props.history.push这个函数跳转到detail页面。在路由组件中加入的代码就是将history这个对象注册到组件的props中去,然后就可以在子组件中通过props调用history的push方法跳转页面。 转载于:https://www.cnblogs.com/jiangningjn/p/11574327.html
相关 create-react-app 搭建 有ReactRouterDom 和 Mobx 项目 create-react-app 搭建 有ReactRouterDom 和 Mobx 项目 1. 下载 create-react-app npm i crea 分手后的思念是犯贱/ 2022年03月14日 18:28/ 0 赞/ 285 阅读
还没有评论,来说两句吧...