【问题标题】:How to hide the sidebar from perticular page in react.js?如何在 react.js 中隐藏特定页面的侧边栏?
【发布时间】:2020-11-09 08:29:29
【问题描述】:

我正在使用 react 实现全局导航侧边栏(左侧可折叠),但我想从某些路由或组件中排除或隐藏我的侧边栏。

当我将它导入特定组件时,我失去了组件响应能力。

import React from "react";
//more imports are here

const App = () => (
  <ThemeProvider theme={theme}>
    <div>
      <AppToolbar />
      <div className="myclass">
        <SideBar>
          <Route path="/" exact component={Home} />
          <Route path="/setting" component={Setting} />
          <Route path="/help" component={Help} />
          <Route path="/about" component={About} />
        </SideBar>
      </div>
    </div>
  </ThemeProvider>
);

export default App;

寻找从Route path="/" exact component={Home} /&gt; 路由隐藏侧边栏的解决方案。 或者有没有其他方法可以实现相同的功能。

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:

    看起来需要先从 SideBar JSX 中取出路由,这样路由就不会无限期地包裹在 SideBar 中。

    传递一个函数 props 给路由组件,它可以改变父组件侧边栏的状态。然后在要隐藏侧边栏的路径上,调用该函数将 SideBar JSX 从 DOM 中取出。

    例子:

    import React from "react";
    //more imports are here
    
    const App = () => {
    const [showSidebar,setShowSidebar] = React.useState();
    
    const handleToggleSideBar = () => {
    //togglesidebar with useState
    setShowSidebar(!showSidebar);
    }
    
     return (
      <ThemeProvider theme={theme}>
        <div>
          <AppToolbar />
          <div className="myclass">
            {showSidebar &&  <SideBar />}
              <Route path="/" exact render={(props) => <Home  toggleSideBar={handleToggleSideBar } {...props} />} />
              <Route path="/setting" render={//do the same thing like Home} />
          </div>
        </div>
      </ThemeProvider>
    )};
    
    export default App;
    

    Home.jsx

        export const Home = ({toggleSideBar}) => {
        useEffect(() => {
          toggleSideBar();
          },[]);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 1970-01-01
      相关资源
      最近更新 更多