ReactJS delay onChange while typing

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

    You can debounce on the onChange event (if the user is typing the onchange event will not execute)

    Warning - Keep in mind that creating functions on render is a bad practice. I did it in order to illustrate the solution. A more safe solution is to use a class Component that creates the debounced handler on its constructor.

    class DebouncedInput extends React.Component {
      constructor() {
        super();
    
        // Creating the debouncedOnChange to avoid performance issues
    
        this._debouncedOnChange = _.debounce(
          this.props.onChange, 
          this.props.delay
        );
      }
    
      render () {
        const { onChange, delay, ...rest } = this.props;
        return (
          
        )
      }
    }
    

    Example below

    function DebouncedInput (props) {
      const { onChange, delay = 300, ...rest } = props;
     
      
      return (
        
      )
    }
    
    function App() {
      return (
        
    console.log('changing')} />
    ) } ReactDOM.render( , document.querySelector('#app') );
    
    
    
      
      
      JS Bin
      
      
      
    
    
     

提交回复
热议问题