【问题标题】:How to hide/show a component inside another component in ReactJS如何在 ReactJS 中隐藏/显示另一个组件内的组件
【发布时间】:2019-09-11 06:29:54
【问题描述】:

我的应用程序如下所示..

import FirstComponent from "./components/firstComponent";
import NextComponent from "./components/nextComponent";
import MyProgressComponent from "./components/progressComponent";

class App extends React.Component {
render() {
  return (
    <Router>
        <div>
            <MyProgressComponent />
            <Route path="/" exact component={FirstComponent} />
            <Route path="/nextComponent" component={NextComponent} />   
        </div>
    </Router>
  );
}
}

正如我们所见,'MyProgressComponent' 在“http://localhost:3000/”和“http://localhost:3000/nextComponent”之间导航时可见,因为它直接嵌套在 App 组件中的 Router 组件下。但我希望'MyProgressComponent' 仅在“http://localhost:3000/nextComponent”中可见并隐藏在“http://localhost:3000/”中。有什么建议吗?

我可以通过在每个 component 中根据需要导入 'MyProgressComponent' 来做到这一点,但我不想在每个 component 中复制它。

【问题讨论】:

  • 如果您不想在每个文件中都导入它,您只需添加一个条件,使 MyProgressComponent 在路径为时不显示 /
  • 你可以做一件事,你可以在NextComponent里面导入MyProgressComponent

标签: javascript reactjs react-component


【解决方案1】:

您可以使用以下语法渲染多个组件

<Route path="/nextComponent" render={() => 
 <>
  <MyProgressComponent />
  <NextComponent />
 </>
} 
/> 

【讨论】:

  • 很好,我也喜欢这个解决方案
【解决方案2】:

根据@Crocsx 评论,您可以对您的代码进行以下检查。

<Router>
  <div>
    {this.props.location.pathname === "/nextComponent" ?  <MyProgressComponent />: null}
    <Route path="/" exact component={FirstComponent} />
    <Route path="/nextComponent" component={NextComponent} />
  </div>
</Router>

【讨论】:

    【解决方案3】:

    您可以使用路由器提供的开关来实现。

    像下面这样的东西应该适合你。

    <Switch>
      <Route exact path="/nextComponent" component={MyProgressComponent} />
    </Switch>
    <Switch>
      <Route path="/" exact component={FirstComponent} />
      <Route path="/nextComponent" component={NextComponent} /> 
    </Switch>
    

    更多文档在这里https://reacttraining.com/react-router/web/guides/basic-components

    【讨论】:

      猜你喜欢
      • 2014-03-30
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      相关资源
      最近更新 更多