英文:
Apply onBlur to form elements but not to the reset button
问题
I can translate the provided code for you. Here's the translated code:
我正在使用一个具有onBlur定义的表单。我现在想在表单内添加一个按钮来重置它。但是当我添加了按钮后,它也附加了onBlur,因此现在点击按钮不起作用,只有在我从按钮上移开时才执行。
这是我的代码的一个非常简化版本:
<form onBlur={handleBlur} onReset={onClear}>
<label>
输入1
<input type="text"/>
</label>
<label>
输入2
<input type="text"/>
</label>
<button type="reset">重置</button>
</form>
Is there anything else you'd like to translate?
英文:
I'm working with a form that has onBlur defined on it. I would now like to add a button within the form to reset it. But when I added the button, it attached the onBlur to it, so now clicking the button doesn't work and it only executes when I tab away from the button.
Here's a very condensed version of my code:
<form onBlur={handleBlur} onReset={onClear}>
<label>
Input1
<input type="text"/>
</label>
<label>
Input2
<input type="text"/>
</label>
<button type="reset">Reset</button>
</form>
I imagine one solution would be to attach the onBlur to each input, instead of on the <form>
, but that would be a large refactor based on the code I haven't shown. So I am wondering if there is a different way.
答案1
得分: 1
你需要阻止模糊事件从按钮元素传播到表单元素。这是JavaScript中的事件传播概念。基本上,每个事件都会从子元素传播到父元素。所以你可以使用 event.stopPropagation()
来阻止它。
<form onBlur={handleBlur} onReset={onClear}>
<label>
Input1
<input type="text" />
</label>
<label>
Input2
<input type="text" />
</label>
<button onBlur={(e) => e.stopPropagation()} type="reset">
Reset
</button>
</form>;
英文:
you need to stop the propagation of blur event from button element to form element. This is a javascript concept called event propagation. Basically every event will propagate from their child to parent. So u can prevent it using event.stopPropagation()
<form onBlur={handleBlur} onReset={onClear}>
<label>
Input1
<input type="text" />
</label>
<label>
Input2
<input type="text" />
</label>
<button onBlur={(e) => e.stopPropagation()} type="reset">
Reset
</button>
</form>;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论