![](/img/trans.png)
[英]jQuery .click() doesn't fire when element is being modified with .text()
[英]Element click doesn't fire when the element gets hidden
我在按钮上切换的文本输入上有一个模糊事件(用 React 渲染它)。 当您单击按钮时,模糊事件会在文本输入上触发,从而从 DOM 中删除按钮,但不会触发按钮单击事件。 我尝试在 100 毫秒的超时时间内包装从 DOM 中删除按钮的代码,它可以工作但感觉很糟糕,有没有更好的方法?
这是代码的要点:
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>
)
这很简单,您只需要使用不同的事件触发器。 onClick 为时已晚,直到 textarea 模糊发生后才会触发,但 onMouseDown 会在其之前触发:
const btn = document.getElementById('btn'); const txt = document.getElementById('txt'); btn.onclick=()=> { console.log("button onClick fired"); } txt.onblur = () => { console.log("Textarea blur 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>
由于您有条件地呈现按钮:
{showInput && <button onClick={buttonHandler}>Apply to all</button>}
一旦您将showInput
设置为 falsy 值,它就会从 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 中删除。
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>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.