【问题标题】:Automatically close dropdown when a new dropdown is selected/opened (React)选择/打开新下拉列表时自动关闭下拉列表(React)
【发布时间】:2019-09-06 00:08:37
【问题描述】:

我有一个下拉组件,我希望能够在您单击其他下拉菜单项时自动关闭上一个下拉菜单。我有下拉组件工作,但在选择新项目后我无法让它们关闭。此外,如果您单击页面上的任意位置,我想关闭这些项目。任何帮助将不胜感激,在此先感谢!

export const Dropdown: FC<Props> = ({ passedBindings }) => {
  let [isDropdownOpen, setDropdownOpen] = useState(false);
  const [ firstMediaBindings, ...restMediaBindings ] = bindings.mediaFlagBindings||[{}];

  const toggleDropdown = () => {
    setDropdownOpen(!isDropdownOpen)
  };

  return (
    <div { ...optionalAttributes }>
        <Container>
          {
            firstMoleculeMediaFlag()
          }
          {isDropdownOpen && restMediaBindings.length > 0 &&
            <Container passedBindings={({
              padding: {
                direction: "all",
                size: "size2"
              }
            })}>
              {
                restMediaBindings.map((mediaFlagBindings: IMoleculeMediaFlag, index: number) => {
                  return (
                    <Container
                      key={index}
                      passedBindings={({
                        padding: {
                          direction: "all",
                          size: "size1"
                        }
                    })}>
                      <MediaFlag key={index} passedBindings={mediaFlagBindings} />
                    </Container>
                  )
                })
              }
            </Container>
          }
        </Container>

      </Container>
    </div>
  )

``

【问题讨论】:

  • “页面上的任何地方”可以通过透明的模态 div 或 on blur 事件来实现;不过有好处也有坏处!

标签: javascript reactjs typescript state react-hooks


【解决方案1】:

您需要一个背景 DIV 以允许单击并退出页面上的任意位置。

这就像一个 3 层系统。

  • 第一:您的页面内容
  • 第二个:背景在顶部
  • 第三:您的下拉菜单位于背景之上

一个示例(使用styled-components 表示样式,但您可以根据需要设置样式):

Backdrop.js

这会在您的页面内容之上呈现一个 div。

const Backdrop = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.2);
  z-index: 100;
`;

像这样使用它:有条件地使用isDropdownOpen

Dropdown.js

但请记住使用z-index 设置下拉菜单的样式,其设置要高于您在背景中使用的z-index。在此示例中,我使用 100 作为背景,因此您可以使用 200。

export const Dropdown() {
  ...
  return(
    isDropdownOpen ?
      <Backdrop onClick={toggleDropdown}/>
      // Here goes the rest of your return for your dropdown
  );
}

如果您需要一个下拉菜单来在单击它们时关闭上一个下拉菜单,您需要在您的 state 中提供一些内容来告诉您打开了哪个下拉菜单。

类似:

const [indexDropdownOpened, setIndexDropdownOpened] = useState(false);

您可以在没有打开下拉菜单时将其设置为false(初始值),您可以使用index(或key)设置它来告诉您的组件哪个是openend。

在每个下拉列表中,当您渲染它们时:

...
return(
  <Container
    key={index}
    onClick={()=>setIndexDropdownOpened(index)}
  />
);

然后,在背景上,你可以这样做:

<Backdrop onClick={()=>setIndexDropdownOpnened(false)}/> // So it closes the dropdown

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2011-11-03
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多