【问题标题】:Make background darker when sidebar is open in React + Typescript在 React + Typescript 中打开侧边栏时使背景变暗
【发布时间】:2021-11-09 10:43:48
【问题描述】:

我正在尝试使用 react-pro-sidebar 和 React + Typescript 自定义侧边栏。 侧边栏看起来不错,但是当侧边栏打开时,我无法使屏幕的其他部分颜色变深。

另外,我想将打开/关闭侧边栏的按钮设置为单独的按钮。这种情况下可以吗?

到目前为止,这是我的代码的工作沙箱:https://codesandbox.io/s/sleepy-lichterman-qqpp5?file=/src/App.tsx

同样的代码放在这里:

import * as React from "react";
import { useEffect, useState } from "react";
import { ProSidebar, Menu, MenuItem, SubMenu } from "react-pro-sidebar";

import "react-pro-sidebar/dist/css/styles.css";
export interface SidebarProps {
  onChange?: (event: React.MouseEvent, isChecked?: boolean) => void;
  isCheckedInitial: boolean;
}

export function Sidebar({ onChange, isCheckedInitial, ...rest }: SidebarProps) {
  const [isChecked, setCheckedState] = useState(isCheckedInitial);

  useEffect(() => {
    setCheckedState(isCheckedInitial);
  }, [isCheckedInitial]);

  const handleChange = (event: React.MouseEvent) => {
    setCheckedState(!isChecked);
    onChange && onChange(event, isChecked);
  };

  return (
    <ProSidebar collapsed={isChecked}>
      <Menu iconShape="square">
        <MenuItem onClick={handleChange}>click </MenuItem>
        <SubMenu title="Top 1">
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
        </SubMenu>
        <SubMenu title="Top 2">
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
        </SubMenu>
        <SubMenu title="Top 3">
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
        </SubMenu>
      </Menu>
    </ProSidebar>
  );
}

export default Sidebar;

【问题讨论】:

    标签: javascript reactjs typescript react-hooks sidebar


    【解决方案1】:

    您可以为此使用定位为divfixed。我在这里编辑了你的例子:https://codesandbox.io/s/kind-babycat-cg872

    我在侧边栏添加了button 和覆盖div

    <button onClick={handleChange}>click me</button>
    // <ProSidebar ...
    <div
        className={`overlay ${!isChecked ? 'visible' : ''}`}
        onClick={handleChange}
    />
    

    并添加了一些css:

    button {
        position: relative;
        z-index: 1;
    }
    
    .overlay {
        position: fixed;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.5);
        opacity: 0;
    }
    
    .overlay.visible {
        right: 0;
        bottom: 0;
        opacity: 1;
        transition: opacity 0.4s;
    }
    

    【讨论】:

    • 感谢您的回答,它解决了较暗背景的问题。与单独的按钮相关,这不是预期的,当按钮设置为“关闭”时是否可以隐藏所有侧边栏?类似于此示例 (bootsnipp.com/snippets/y3O1),但按钮固定在其上方且始终可见。
    • 侧边栏组件支持collapsedWidth 属性。我相应地更新了代码框链接,以便侧边栏折叠到0px
    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多