gpt4 book ai didi

javascript - React-router-dom 页面导航

转载 作者:行者123 更新时间:2023-12-03 14:29:47 24 4
gpt4 key购买 nike

尝试使用 react-router-dom 进行简单导航。设法让它与 this.props.history.push('/pathName'); 一起工作但是,我对我的理解和实现有疑问,感谢您纠正我的错误的 2 美分。

我的方向正确吗?

我的用例场景:

首先,我有 3 个带有公共(public)组件的页面 <Navbar>在每个页面的顶部实现。 Navbar由 2 个按钮页面 A 和页面 B 组成。单击相应按钮时,用户应导航到任一屏幕。

  1. 主页
  2. 页面A
  3. B页

我的实现:

Homepage.js -(除了类名不同之外,Page A 和 B 的实现相同)

import React from 'react';
import { Redirect } from "react-router-dom";

import Navbar from '../common/navbar';

class Homepage extends React.Component{

callBackFromNavBar = (value) => {
NavigationHelper.historyPush(this.props, value);
}

render(){

return (
<div>
<Navbar callback={this.callBackFromNavBar}/>
</div>
);
}
}

export default Homepage;

NavigationHelper.js

export const historyPush = (props,value) => {
console.log('helper calling');
switch(value){
case 'PageA':
props.history.push('/PageA');
break;
case 'PageB':
props.history.push('/PageB');
break;
default:
break;
}
}

导航栏 - 下面显示了如何将传递回父级

<Button variant="contained" onClick={ () => {
props.callback('PageA');
} }>Page A</Button>

学习来源:

  1. https://dev.to/projectescape/programmatic-navigation-in-react-3p1l

链接到沙盒

https://codesandbox.io/embed/react-router-dom-navigation-4tpzs?fontsize=14&hidenavigation=1&theme=dark

最佳答案

我会尝试这样的事情来简化事情

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import PageA from './'
import PageB from './'

function App() {
return (
<Router>
<Navbar />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/pageA" component={PageA} />
<Route exact path="/pageB" component={PageB} />
</Switch>
</Router>
);
}

然后在您的导航栏组件中只需设置 <Link>对于每个页面,我在 App.js 文件中设置了路由,但是我看到人们只是使用专用组件进行路由,但找到最适合您的内容

关于javascript - React-router-dom 页面导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60913206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com