键入时 ReactJS 延迟 onChange [英] ReactJS delay onChange while typing

查看:130
本文介绍了键入时 ReactJS 延迟 onChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更改状态以维护用户输入的字符串.但是我想延迟一个动作,直到用户停止输入.但我不能完全确定如何做到这两点.

I need the state to change to maintain the string the user is typing. However I want to delay an action until the user stops typing. But I can't quite place my finger on how to do both.

所以当用户停止输入时,我希望触发一个动作,但不是之前.有什么建议吗?

So When the user stops typing I want an action to be triggered, but not before. Any suggestions?

推荐答案

With React Hooks 和 Function 组件

要保留用户正在输入的字符串,请使用 useState 挂钩来存储用户正在输入的文本.然后将该状态赋予输入的值.另外一定要在输入的onChange事件处理器上使用setState,否则输入值不会改变.

With React Hooks and Function components

To keep the string the user is typing, use the useState hook to store the text the user is typing. Then give that state to the value of the input. Also be sure to use setState on the onChange event handler of the input, otherwise the input value won't change.

要仅在用户停止输入后的某个时间触发操作,您可以将 useEffect 钩子与 setTimeout 一起使用.在这种情况下,我们希望在输入值发生变化时触发 useEffect,因此我们将创建一个 useEffect 钩子,并在其依赖数组上为其提供值为输入.赋予 useEffect 的函数应该使用 setTimeout 在所需的延迟时间后触发操作.此外,赋予 useEffect 的函数应该返回一个清除超时设置的清理函数.这避免了对不再与用户相关的输入值执行操作.

To trigger an action only sometime after the user stops typing, you can use the useEffect hook together with setTimeout. In this case, we want to trigger useEffect when the input value changes, so we'll create a useEffect hook and on its dependency array give it the variable with the value of the input. The function given to useEffect should use setTimeout to trigger an action after the delay time that is desired. Also, the function given to useEffect should return a cleanup function that clears the timeout set. This avoids doing actions for input values which are no longer relevant to the user.

下面是一个应用的小例子,它使用上述步骤来保持用户输入的字符串可见,并在用户停止输入 500 毫秒后显示完成的字符串.

Below is a little example of an app that uses the above steps to keep the string the user is typing visible and to show the finished string 500ms after the user stops typing.

function App() {
  const [query, setQuery] = useState("");
  const [displayMessage, setDisplayMessage] = useState("");

  useEffect(() => {
    const timeOutId = setTimeout(() => setDisplayMessage(query), 500);
    return () => clearTimeout(timeOutId);
  }, [query]);

  return (
    <>
      <input
        type="text"
        value={query}
        onChange={event => setQuery(event.target.value)}
      />
      <p>{displayMessage}</p>
    </>
  );
}

这篇关于键入时 ReactJS 延迟 onChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆