为了获得用户输入的文本,我尝试使用这个脱附函数。没有取消功能,这是很好的工作(对每个输入的字符触发的问题)。当我尝试使用我的onChange函数时,它不起作用。经过一些研究,我意识到react是在清理事件数据,所以我添加了event.persist()函数,它从池中删除合成事件,并允许用户代码保留对事件的引用。
使用此函数,当我在控制台上打印事件时,我可以看到事件数据。但我无法编写一个代码,可以将此事件传递给onChange函数。
我的函数由输入触发:
const handleOnChange = (onChange) => (e) => {
e.persist();
console.log(e.target);
debounce(onChange, 500);
};
关于输入函数,我有如下所示:
<TextValidator
name="password"
value={password}
onChange={handleOnChange(onChange)}
/>
我有一种感觉,这是一个愚蠢的错误,但我是在数小时前,没有成功地发现哪里的问题。我是不是遗漏了什么?
发布于 2022-05-12 03:58:39
debounce
函数返回函数,但尚未执行。这样你就可以这样想了。
const handleOnChange = (onChange) => (e) => {
e.persist();
console.log(e.target);
debounce(onChange, 500)();
};
这是行不通的,因为每次调用handleOnChange
时,都会创建一个新的退欧函数。您必须保存删除函数的某些位置并重用它。
const debouncedOnChange = debounce((func) => {
fucn();
}, 500);
const handleOnChange = (onChange) => (e) => {
console.log(e.target);
e.persist();
debouncedOnChange(onChange);
};
你可以通过这样的论点
const debouncedOnChange = debounce((func) => {
func();
}, 500);
const handleOnChange = (onChange) => (e) => {
console.log(e.target);
e.persist();
debouncedOnChange(() => onChange(e));
};
如果您使用react <=16,请小心使用事件池。
https://stackoverflow.com/questions/62586914
复制相似问题