英文:
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("");
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 called?
/>
</View>
);
}
答案1
得分: 2
通常,在多个不同的API和事件系统中,当您通过代码更改字段/控件的值时,不会触发与该更改相关的任何事件处理程序。(有一些例外的API/系统,但它们很少见。)事件处理程序用于处理通过UI对字段/控件进行更改时的情况。例如,在DOM的input
元素中,设置value
属性会更改值,但不会触发任何事件(如change
或input
);通过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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论