ReactJS delay onChange while typing

前端 未结 5 1231
臣服心动
臣服心动 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:11

    One way to do this would be to have your onChange handler execute two functions:

    • Function for immediately updating state
    • Debounced function

    Example code:

    import debounce from 'lodash.debounce';
    
    class Foo extends React.Component {
      constructor() {
        super()
    
        this.state = {
          value: ''
        }
    
        // Delay action 2 seconds
        this.onChangeDebounced = debounce(this.onChangeDebounced, 2000)
      }
    
      handleInputChange = (e: Event) => {
        // Immediately update the state
        this.setState({
          value: e.target.value
        })
    
        // Execute the debounced onChange method
        this.onChangeDebounced(e)
      }
    
      onChangeDebounced = (e: Event) => {
        // Delayed logic goes here
      }
    
      render() {
        return (
          
        )
      }
    }
    

提交回复
热议问题