仅在不在给定路线中时才渲染HTML

时间:2017-05-20 17:39:51

标签: reactjs react-router

如果我们不在Life路线中,我怎样才能确保.who课程才出现?

class App extends Component {
  render() {    
    return (
      <div className="App">

        <div className="centered-wrapper">
          <Switch>
            <Route exact path="/" component={Welcome} />
            <Route path="/life" component={Life} />
            <Route path="*" component={Welcome}/>
          </Switch>

        </div>                
        <div className="who">[ <Link to="/life">Who's Marco</Link> ]</div>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

要根据路线编写条件,您需要在App组件中包含路径数据。因此,在导出之前,您需要使用withRouter高阶组件包装App组件。

export default withRouter(App);

现在,您将获得一些与路由器相关的属性作为App组件的道具。您可以使用this.props.location.pathname属性来提供当前浏览器路径,以便在JSX中编写您的条件,如下所示。

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="centered-wrapper">
          <Switch>
            <Route exact path="/" component={Welcome} />
            <Route path="/life" component={Life} />
            <Route path="*" component={Welcome} />
          </Switch>
        </div>
        { (this.props.location.pathname !== "/life") && (<div className="who">[ <Link to="/life">Who's Marco</Link> ]</div>)}
      </div>
    );
  }
}