应用 onBlur 到表单元素,但不应用到重置按钮。

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

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:

&lt;form onBlur={handleBlur} onReset={onClear}&gt;
  &lt;label&gt;
    Input1
    &lt;input type=&quot;text&quot;/&gt;
  &lt;/label&gt;
  &lt;label&gt;
    Input2
    &lt;input type=&quot;text&quot;/&gt;
  &lt;/label&gt;
  &lt;button type=&quot;reset&quot;&gt;Reset&lt;/button&gt;
&lt;/form&gt;

I imagine one solution would be to attach the onBlur to each input, instead of on the &lt;form&gt;, 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()

&lt;form onBlur={handleBlur} onReset={onClear}&gt;
  &lt;label&gt;
    Input1
    &lt;input type=&quot;text&quot; /&gt;
  &lt;/label&gt;
  &lt;label&gt;
    Input2
    &lt;input type=&quot;text&quot; /&gt;
  &lt;/label&gt;
  &lt;button onBlur={(e) =&gt; e.stopPropagation()} type=&quot;reset&quot;&gt;
    Reset
  &lt;/button&gt;
&lt;/form&gt;;

huangapple
  • 本文由 发表于 2023年4月1日 01:03:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75901027.html
匿名

发表评论

匿名网友

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

确定