点击离开监听器与选择组件作为子组件。

huangapple go评论58阅读模式
英文:

Click away listener with select component as a child

问题

以下是翻译好的内容:

在下面的示例中,有一个包含几个元素的容器。除了嵌套的选择元素之外,一切都正常工作。当点击选择时,它被检测为发生在红色容器之外。

CodeSandbox示例

英文:

In example below there is container that contains few elements. Everything works fine instead of nested Select element. When clicking select, it detects as if the click happened outside the red container

Codesandbox example

答案1

得分: 1

问题会在 Select 上使用 disablePortal 后解决。原因是:默认情况下,mui 使用了一个门户(portal)概念,这意味着弹出窗口会被放置在一个完全不同的DOM子树中(作为<body>的最后一个子节点)。这会严重干扰检查冒泡事件是否起源于与您的组件构成的相同子树,或者是否被视为 外部 点击事件。

英文:

The issue goes away if you use disablePortal on the Select. The reason is: by default mui uses a portal concept, which means popups are placed into a completely different DOM sub-tree (located as last child in the &lt;body&gt;). Well this royally messes with checking if bubbling events originated in the same subtree constituted by your component or are considered outside clicks.

          &lt;Select
            labelId=&quot;demo-simple-select-label&quot;
            id=&quot;demo-simple-select&quot;
            value={age}
            label=&quot;Age&quot;
            onChange={handleChange}
            MenuProps={{disablePortal: true}}
          &gt;
            &lt;MenuItem value={10}&gt;Ten&lt;/MenuItem&gt;
            &lt;MenuItem value={20}&gt;Twenty&lt;/MenuItem&gt;
            &lt;MenuItem value={30}&gt;Thirty&lt;/MenuItem&gt;
          &lt;/Select&gt;

huangapple
  • 本文由 发表于 2023年6月26日 16:49:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定