【问题标题】:onBlur Not Working in React Dropdown ComponentonBlur 在 React 下拉组件中不起作用
【发布时间】:2020-01-14 01:15:58
【问题描述】:

我创建了以下 React 下拉组件:

const Dropdown = ({
  titleTag = 'button',
  titleCss,
  title,
  icon,
  menuCss,
  children,
  open,
  ...props
}) => {
  const [isOpen, setIsOpen] = React.useState(false)

  const handleClick = () => setIsOpen(state => !state)
  const handleBlur = () => setIsOpen(false)

  return (
    <DropdownBase>
      <Trigger
        as={titleTag}
        css={titleCss}
        onClick={handleClick}
        onBlur={handleBlur}
      >
        {title}
        {icon}
      </Trigger>
      <Submenu css={menuCss} open={isOpen}>
        {children}
      </Submenu>
    </DropdownBase>
  )
}

我的问题是,如果我在菜单外单击,菜单将不会关闭。我可以通过单击打开和关闭菜单。但是我无法通过单击离开菜单来关闭菜单——这是我认为handleBlur 函数会发生的情况。确实,我将下拉菜单重构为一个组件之前,该功能确实有效。

那么,当我在下拉菜单之外点击时,我必须怎么做才能关闭下拉菜单?

谢谢。

注意:如果相关,这里是构成下拉菜单的相关样式组件:


const DropdownBase = styled.div`
  display: inline-flex;
  position: relative;
  z-index: 10;
`

const Trigger = styled.div`
  cursor: pointer;
`

const Submenu = styled.div`
  display: ${props => (props.open ? 'block' : 'none')};

  position: absolute;
  top: 100%;
  left: 0;
  z-index: 20;

  ${Link} {
    display: inline-block;
    width: 100%;
  }
`

【问题讨论】:

  • 尝试给组件一个tabindex
  • 处理程序应该像const handleBlur = () =&gt; setIsOpen(state =&gt; false);吗?
  • @URL87 我做了,没区别。
  • @MarkusZeller 我也试过了——没用。

标签: javascript reactjs dropdown styled-components react-component


【解决方案1】:

div 元素无法接收focus 事件,您可以将tabindex="0" 添加到您的Trigger 组件中。

can you see this

【讨论】:

  • 我将Trigger 组件更改为button 标签,现在可以使用了,谢谢。请注意处于类似情况的其他人,tabindex="0" 对我没有工作。
  • 更正: tabindex 确实有效 - 但是,我忘记将“i”大写。换句话说,是tabIndex="0"不是 tabindex="0"
猜你喜欢
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-06
相关资源
最近更新 更多