TextInput的`.clear()`为什么不触发`onChangeText`回调?

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

Why TextInput's `.clear()` doesn't trigger `onChangeText` callback?

问题

I am programmatically clearing the TextInput's value via .clear() method.
I also subscribed my state to onChangeText but on .clear() invocation, my state doesn't change.

Why .clear() doesn't trigger onChangeText? Isn't it changing the text value?

Example:

function MyComponent() {
  const [value, setValue] = useState("");
  const ref = useRef();

  const handlePress = () => {
    ref.current.clear();
  };

  return (
    <View>
      <TextInput onChangeText={setValue} ref={ref} />;
      <Button
        title="clear"
        onPress={handlePress} // <<< when this is called, onChangeText doesn't get called?
      />
    </View>
  );
}
英文:

I am programmatically clearing the TextInput's value via .clear() method.
I also subscribed my state to onChangeText but on .clear() invocation, my state doesn't change.

Why .clear() doesn't trigger onChangeText? Isn't it changing the text value?

Example:

function MyComponent() {
  const [value, setValue] = useState(&quot;&quot;);
  const ref = useRef();

  const handlePress = () =&gt; {
    ref.current.clear();
  };

  return (
    &lt;View&gt;
      &lt;TextInput onChangeText={setValue} ref={ref} /&gt;;
      &lt;Button
        title=&quot;clear&quot;
        onPress={handlePress} // &lt;&lt;&lt; when this is called, onChangeText doesn&#39;t called?
      /&gt;
    &lt;/View&gt;
  );
}

答案1

得分: 2

通常,在多个不同的API和事件系统中,当您通过代码更改字段/控件的值时,不会触发与该更改相关的任何事件处理程序。(有一些例外的API/系统,但它们很少见。)事件处理程序用于处理通过UI对字段/控件进行更改时的情况。例如,在DOM的input元素中,设置value属性会更改值,但不会触发任何事件(如changeinput);通过submit函数提交表单不会触发submit事件。React Native只是遵循其字段/控件中的相同模式。

英文:

In general across multiple different APIs and event systems, when you change the value of a field/control via code, it doesn't trigger any event handlers related to that change. (There are APIs/systems that are exception to that general rule, but they're rare.) The event handlers are there for when the change is done via the user operating on the field/control in the UI. For example, with a DOM input element, setting the value property changes the value, but doesn't trigger any events (such as change or input); submitting a form via its submit function doesn't trigger a submit event. React Native is just following the same pattern in their fields/controls.

huangapple
  • 本文由 发表于 2023年5月14日 20:06:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76247396.html
匿名

发表评论

匿名网友

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

确定