元素被隐藏后,点击事件不会触发

4
我在文本输入框上设置了模糊事件,以切换按钮(使用React进行呈现)。当您单击按钮时,文本输入框上的模糊事件触发,将按钮从DOM中删除,但按钮单击事件未触发。我尝试在将按钮从DOM中删除的代码中包装100ms超时,它可以工作但感觉很hacky,有更好的方法吗?
以下是代码要点:
const blurHandler = e => {
  setShowInput(false); //this prevents buttonHandler from being fired

  // setTimeout(() => setShowInput(false), 100); // this works with 100ms, but not with 50ms for example
}

const buttonHandler = e => {
  console.log('Button clicked!');
}

const focusHandler = e => {
  setShowInput(true);
}

return (
  <div>
    <input type="text" onFocus={focusHandler} onBlur={blurHandler} >
    {showInput && <button onClick={buttonHandler}>Apply to all</button>}
  </div>
)

2
一旦您在按钮上按下鼠标,输入框就会触发模糊事件,导致其从DOM中被移除。因此,您永远无法监听按钮的点击事件:点击事件是在鼠标按下和松开之后触发的。 - Terry
2个回答

6
这很简单,您只需要使用不同的事件触发器。onClick 太晚了,它在文本区域失去焦点之后才会触发,但是 onMouseDown 会在此之前触发:

const btn = document.getElementById('btn');
const txt = document.getElementById('txt');

txt.onblur      = () => {console.log("Textarea blur fired")}
txt.onfocus     = () => {console.log("Textarea focus fired")}

btn.onclick     = () => {console.log("Button onClick fired")}
btn.onmousedown = () => {console.log("Button mouseDown fired")}
btn.onmouseup   = () => {console.log("Button mouseUp fired")}
<textarea id="txt">Focus me first</textarea>
<button id="btn">Click me next</button>


2
由于您使用条件渲染来呈现该按钮:
{showInput && <button onClick={buttonHandler}>Apply to all</button>}

一旦您将showInput设置为假值,它将从DOM中删除。您有几个选项:

选项1(如果您不必将按钮从DOM中删除)

return (
  <div>
    <input type="text" onFocus={focusHandler} onBlur={blurHandler} >
    <button style={{opacity: showInput ? 1 : 0}} onClick={buttonHandler}>Apply to all</button>}
  </div>
)

将不透明度设置为0会隐藏按钮,但不会从DOM中删除它。

选项2(如果必须从DOM中删除按钮)

const btnClickedRef = useRef(false)

const buttonHandler = e => {
  console.log('Button clicked!');
  btnClickedRef.current = true
}

return (
  <div>
    <input type="text" onFocus={focusHandler} onBlur={blurHandler} >
    {showInput && btnClickedRef.current && <button onClick={buttonHandler}>Apply to all</button>}
  </div>
)

1
免责声明:我实际上还没有尝试过Option2,所以如果它不起作用,请告诉我:D - Sinan Yaman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接