ReactJS delay onChange while typing

前端 未结 5 1235
臣服心动
臣服心动 2021-02-01 16:28

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

5条回答
  •  借酒劲吻你
    2021-02-01 17:08

    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.

    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.

    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 (
        <>
           setQuery(event.target.value)}
          />
          

    {displayMessage}

    ); }

提交回复
热议问题