显示某个组件时隐藏组件(带反应路由器)

时间:2017-05-11 13:21:20

标签: react-router

我有以下渲染功能。

class App extends Component {
    render() {
        return (
            <Router>
                <div>
                    <Header/>
                    <Switch>
                        <Route exact path="/" component={TestApp}/>
                        <Route exact path="/chat" component={ChahtView1}/>
                        <Route exact path="/chat/invite" component={ChatView2}/>
                        <Route exact path="/chat/chatting" component={ChatView3}/>
                        <Route component={NotFound}/>
                    </Switch>
                </div>
            </Router>
        );
    }
 }

在这种情况下,每个页面都会显示Header个组件。我想要做的是在出现Header组件时隐藏NotFound

我该怎么做?请帮帮我! 感谢。

3 个答案:

答案 0 :(得分:1)

我有同样的问题。 我找到的唯一方法是从子组件更改组件的状态并在其状态上显示<Header />

所以,首先我添加了showHeader状态和函数,这将伪造此状态,将此函数传递给<NotFound />

class App extends Component {

  constructor (props) {
    super(props)
    this.state = {
      showHeader: true
    }
  }

  hideNavigation = () => {
    this.setState({
      showHeader: false
    })
  }

  render() {
    return (
      <Router>
        <div>
          {this.state.showHeader && <Header/>}

          <Switch>
            <Route exact path="/" component={TestApp}/>

            <Route render={ (props) => (
                <NotFound
                    hideNavigation={this.hideNavigation}
                    {...props}
                />
              )}
            />
          </Switch>
        </div>
      </Router>
    );
  }
}

然后从hideNavigation()组件调用<NotFound />

class NotFound extends Component {

  componentWillMount () {
    this.props.hideNavigation()
  }

  render() {
    return (
      <div>
          <h1>Ooops!</h1>
      </div>
    );
  }
}

答案 1 :(得分:1)

您可以使用react-router-dom中'withRouter'提供的'location'对象来有条件地显示或隐藏组件,如:

const Main = withRouter(({location}) => (
<div>
 {location.pathname !== "/" && <Header/>}
   <Switch location={location}>
    <Route path="/" exact component={HomePage}/>
    <Route path="/first-page" component={First}/>
    <Route path="/second-page" component={Second}/>
    <Footer />
   </Switch>
<div>
)

有关'位置'的更多信息,请访问:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

答案 2 :(得分:0)

自从React Router 5.1开始,就有了hook useLocation,您可以通过它方便地访问当前位置。

import { useLocation } from 'react-router-dom'

function HeaderView() {
  let location = useLocation();
  console.log(location.pathname);
  return <span>Path : {location.pathname}</span>
}