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 (
<>
<input
type="text"
value={query}
onChange={event => setQuery(event.target.value)}
/>
<p>{displayMessage}</p>
</>
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…