我是React的新手,正在尝试向Material-UI(版本4.0.1)的AppBar组件添加“主页”页面链接。我想看到的行为是,当单击“主页”链接时,将显示组件“ OnePage”。
在“ OnePage”中,有一个指向另一个组件“ TwoPage”的链接,该链接应该是单击“ ViewTwo page”时显示的唯一内容。但是,当前同时显示了OnePage和TwoPage。
对解决导航问题的任何帮助将不胜感激!
以下是相关文件。
App.js
import React from 'react';
import './App.css';
import SearchBar from './SearchBar';
import OnePage from './OnePage';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<div className="App">
<Router>
<div>
<SearchBar />
<Switch>
<Route path="/" exact component={OnePage} />
</Switch>
</div>
</Router>
</div>
);
}
export default App;
SearchBar / index.js
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import { NavLink, withRouter } from 'react-router-dom';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
function SearchBar() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="Menu">
<MenuIcon />
</IconButton>
<NavLink to="/">
<Typography variant="h6" className={classes.title}>
Home
</Typography>
</NavLink>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
export default withRouter(SearchBar);
OnePage / index.js
import React from 'react';
import { BrowserRouter as Router, Route, Link, withRouter } from 'react-router-dom'
import { Container } from '@material-ui/core';
import TwoPage from '../TwoPage';
class OnePage extends React.Component {
render() {
return (
<Container>
<Router>
<div>
<span>Test Page 1</span>
</div>
<div>
<Link to='/twoPage'>View Two page</Link>
</div>
<Route path="/twoPage" exact render={() => <TwoPage />} />
</Router>
</Container>
)
}
}
export default withRouter(OnePage);
TwoPage / index.js
import React from 'react';
class TwoPage extends React.Component {
render() {
return (
<div>
<span>Test Page 2</span>
</div>
)
}
}
export default TwoPage;
答案 0 :(得分:1)
问题是您要在新的Router
组件内定义第二页。您应该具有一个根Router
组件才能正常工作。如果您使用withRouter
来指向<Link/>
<Route/>
HOC包装
工作示例:-
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
function BasicExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={OnePage} />
<Route path="/twoPage" component={TwoPage} />
</div>
</Router>
);
}
function OnePage() {
return (
<div>
<li>
<Link to="/twoPage">Two Page</Link>
</li>
</div>
);
}
function TwoPage() {
return (
<div>
<h2>TwoPage</h2>
</div>
);
}
export default BasicExample;