连接没有父子连接的反应钩子组件

时间:2021-05-27 13:06:10

标签: javascript reactjs show-hide

我想连接一个没有父子连接的反应组件,但我想显示和隐藏另一个组件的子组件。

这是代码:

import React, { useEffect } from "react";
import DashSidebar from "./DashSidebar";
import Catalog from "./components/catalog";

function Dashboard() {
  useEffect(() => {
    document.title = "Home";
  }, []);

  return (
    <div id="l-dashboard">
      <DashSidebar />
      <Catalog />
    </div>
  );
}

export default Dashboard;

我在 DashSidebar 中有一个按钮,我想显示和隐藏 Catalog

为什么我不让它成为父母和孩子?

因为DashSidebar是一个固定位置,它是左侧的侧面板,而我想在右侧显示和隐藏内容..

enter image description here

2 个答案:

答案 0 :(得分:1)

由于您使用的是 react-router,因此可以通过以下步骤完成。

  1. 使用 Link 组件将您的目录列表包裹在侧边栏中。
  2. 现在在 Route 的帮助下呈现右侧的目录。

请参考沙箱

React SideBar Example

答案 1 :(得分:0)

Lift the state 通过在 DashSidebar 的 props 中传递一个函数来改变 Dashboard 状态中的变量,从而使 Catalog 对 Dashboard 组件的可见性。在 Catalog 的 props 中传递变量以控制其可见性。