一个元素有两个相反的`useState`的`onClick`事件。

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

One element having two onClick events with opposite useState

问题

import React, { useState } from "react";

export default function App() {
  const [showList, setShowList] = useState(false);
  return (
    <div className="" onClick={() => setShowList(false)}>
      <h1>Welcome Here</h1>
      <button onClick={() => setShowList(true)}>Click here</button>
      {showList && (
        <ul>
          <li>1</li>
          <li>2</li>
          <li>3</li>
        </ul>
      )}
    </div>
  );
}
英文:

I'm trying to use a custom dropdown with a useState hook. I want to show the list when button is clicked but want to hide when user clicks anywhere outside the button. So, I'm having onClick events on parent div and button, but the onClick event of parent div triggers even when clicking the button, preventing the button to show the list.
Here is the code:

import React, { useState } from &quot;react&quot;;
    
export default function App() {
  const [showList, setShowList] = useState(false);
  return (
    &lt;div className=&quot;&quot; onClick={() =&gt; setShowList(false)}&gt;
      &lt;h1&gt;Welcome Here&lt;/h1&gt;
      &lt;buton onClick={() =&gt; setShowList(true)}&gt;Click here&lt;/buton&gt;
      {showList &amp;&amp; (
        &lt;ul&gt;
          &lt;li&gt;1&lt;/li&gt;
          &lt;li&gt;2&lt;/li&gt;
          &lt;li&gt;3&lt;/li&gt;
        &lt;/ul&gt;
      )}
    &lt;/div&gt;
  );
}

And this is the codesandbox example: https://codesandbox.io/s/custom-dropdown-ycq90y?file=/src/App.js:0-426

答案1

得分: 1

你需要停止事件的传播:

&lt;button
  onClick={(event) =&gt; {
    event.stopPropagation() // &lt;--- 这会阻止事件冒泡到树上层
    setShowList(true)
  }}
&gt;
  点击这里
&lt;/button&gt;

这并不是React特有的,React只是为其合成事件包装了本地行为。

英文:

You need to stop the propagation of the event:

&lt;button
  onClick={(event) =&gt; {
    event.stopPropagation() // &lt;--- this makes the event not bubble up the tree
    setShowList(true)
  }}
&gt;
  Click here
&lt;/button&gt;

This is not React specific, React is only wrapping the native behaviour for it's synthetic events.

huangapple
  • 本文由 发表于 2023年5月17日 16:07:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269850.html
匿名

发表评论

匿名网友

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

确定