我正在学习reactjs,并且试图在“主页”部分中显示搜索栏,并在“商店”部分(或其他部分)中将其消失。
为了更好地理解,我给您提供了一张参考图片:The final result must be like this
这是我组件的代码:
import React, {Component} from 'react';
import {Nav, Button, Navbar, Form, FormControl} from 'react-bootstrap';
import {NavLink} from 'react-router-dom';
import {AuthButton} from '../App';
import logo from '../img/logo.png'
class Header extends Component{
render(){
return(
<>
<Navbar>
<div>
<img src={logo} className='main-logo'/>
</div>
<Form className='form'>
<Button className='btn-search'/>
<FormControl type="text" placeholder="Search..." className='barra'/>
</Form>
<Nav className="ml-auto">
<NavLink className= 'nav-link' to='/'>Home</NavLink>
<hr className='hr-header'/>
<Nav.Link className= 'nav-link'>About</Nav.Link>
<hr className='hr-header'/>
<NavLink className= 'nav-link' to='/Shop'>Shop</NavLink>
<hr className='hr-header'/>
<Nav.Link className= 'nav-link'>Help</Nav.Link>
</Nav>
<NavLink to='/Shopping'>
<Button className='btn-cart' variant="secondary">
Your Cart
</Button>
</NavLink>
<AuthButton/>
</Navbar>
</>
)
}
}
export default Header;
这就是我将组件导入路由器的方式
import React from 'react';
import './styles/App.css';
import Shop from './container/shop';
import Shopping from './container/shopping';
import Shipping from './container/shipping';
import Payment from './container/payment';
import home from './container/home';
import Product from './container/Product';
import iPhone from './container/iPhone';
import iPad from './container/iPad';
import SignInForm from './components/SignInForm';
import {BrowserRouter as Router, Route, withRouter, Redirect, Switch} from 'react-router-dom';
import {Button, ButtonToolbar, OverlayTrigger, Popover} from 'react-bootstrap';
function App(){
return (
<Router>
<Route>
<Switch>
<Route exact path='/' component={home}/>
<Route path='/Shop' component={Shop}/>
<Route path='/Product' component={Product}/>
<Route path='/iPhone' component={iPhone}/>
<Route path='/iPad' component={iPad}/>
<PrivateRoute path='/Shopping' component={Shopping}/>
<Route path='/Shipping' component={Shipping}/>
<Route path='/Payment' component={Payment}/>
<Route path='/SignInForm' component={SignInForm}/>
<Route path='*' component={() => <div
style = {{
textAlign: 'center',
paddingTop: 250,
fontSize: 30
}}>
<strong>404 NOT FOUND</strong>
</div>}/>
</Switch>
</Route>
</Router>
);
}
export default App;
我还有其他文件.js用于我的小节
谢谢大家!
答案 0 :(得分:2)
如果为Nav和Search创建单独的组件,则生活会变得更加轻松。将您的Search组件放置在Nav组件内,然后仅在某些地址(即/ Shop以外的任何地址)呈现Search。
import React from "react";
import { withRouter } from "react-router-dom";
import Nav from "/.Nav";
function SearchComponent() {
return <div>My search bar</div>;
}
function MyComponent(props) {
const path = props.location.pathname;
return (
<div>
<Nav>{path !== "/Shop" && <SearchComponent />}</Nav>
</div>
);
}
export default withRouter(MyComponent);
此技术公开location至withRouter以获得当前路径(/ pageName)。然后,如果位置为“ / Shop”,它将使用conditional rendering隐藏搜索。