所选组件不应该显示菜单



目标:
当选择" Home "而不选择" About "时显示导航菜单

问题:
今天,如果你选择导航链接Home或About,你总是会看到菜单。

是否可以在不显示导航菜单的情况下选择"About"?

Info:
*我是新手在Reactjs
*导航的列表可以是许多链接,例如20个不同的链接或更少。例如,索引,约,服务,联系我们等。
*这是一个简化的版本,当你只有两个链接,是家,约。实际上它可以是菜单中更多的导航链接。

Stackblitz: https://stackblitz.com/edit/react-k19hye?

谢谢!


import React from 'react';
import './style.css';
import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const Nav = () => (
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</div>
);
const HomePage = () => <h1>Home Page</h1>;
const AboutPage = () => <h1>About Page</h1>;
export default class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
};
}
render() {
return (
<Router>
{/* Router component can have only 1 child. We'll use a simple
div element for this example. */}
<div>
<Nav />
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutPage} />
</div>
</Router>
);
}
}
render(<App />, document.getElementById('root'));

这样做的一个简单方法是使用Switch并将AboutPage路由移动到Nav之前。这样,如果您有很多页面,就不必为每个组件添加Nav

import React from 'react';
import './style.css';
import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
const Nav = () => (
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</div>
);
const HomePage = () => <h1>Home Page</h1>;
const AboutPage = () => <h1>About Page</h1>;
export default class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
};
}
render() {
return (
<Router>
{/* Router component can have only 1 child. We'll use a simple
div element for this example. */}
<Switch>
<Route path="/about" component={AboutPage} />
<div>
<Nav />
<Route exact path="/" component={HomePage} />
</div>
</Switch>
</Router>
);
}
}
render(<App />, document.getElementById('root'));

相关内容

  • 没有找到相关文章

最新更新