如果在内部单击,则 OnBlur 关闭反应组件

我使用 Material UI 创建了一个 React 组件,如下所示


<Popper

  open={open}

  anchorEl={anchorRef.current}

  onBlur={handleToggle}

  transition

  disablePortal

>

  <MenuList autoFocusItem={open}>

    <MenuItem>Tom</MenuItem>

    <MenuItem>Patt</MenuItem>

  </MenuList>

  <input type="text" name="Student" onChange={getStudent}></input>

</Popper>

在上面的组件中,我有MenuList和TextField。我试图补充 onBlur={handleToggle}一点,如果在组件外部单击它会关闭组件,但即使我试图在TextFieldusing中添加文本也会关闭它onChange={getStudent},为什么会发生这种情况以及如何仅在组件外部单击时关闭组件?谢谢。


30秒到达战场
浏览 88回答 1
1回答

开心每一天1111

您可以使用ClickAwayListener组件来检测用户是否在区域外单击Popover。<ClickAwayListener onClickAway={() => setOpen(false)}>&nbsp; <span>&nbsp; &nbsp; <Popper&nbsp; &nbsp; &nbsp; open={open}&nbsp; &nbsp; &nbsp; anchorEl={ref.current}&nbsp; &nbsp; &nbsp; transition&nbsp; &nbsp; &nbsp; disablePortal&nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; <MenuList autoFocusItem={open}>&nbsp; &nbsp; &nbsp; &nbsp; <MenuItem>Tom</MenuItem>&nbsp; &nbsp; &nbsp; &nbsp; <MenuItem>Patt</MenuItem>&nbsp; &nbsp; &nbsp; </MenuList>&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp; &nbsp; &nbsp; &nbsp; name="Student"&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </Popper>&nbsp; &nbsp; <Button variant="outlined" onClick={() => setOpen((o) => !o)} ref={ref}>&nbsp; &nbsp; &nbsp; Nothing&nbsp; &nbsp; </Button>&nbsp; </span></ClickAwayListener>现场演示https://codesandbox.io/s/63953850onblur-closing-react-component-if-clicked-inside6395464363954643-brih9?file=/demo.tsx
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript