ReactJS delay onChange while typing

前端 未结 5 1243
臣服心动
臣服心动 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 16:59

    Sounds you are going to need to use setTimeout to start a timer as soon as the user enters text. If the user enters another character, restart the timer. If the user does not type again before the timer completes, it will fire an action that toggles the checkbox:

    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          text: '',
          checked: false
        };
        this.timer = null;
      }
      
      componentDidUpdate (prevProps, prevState) {
        if(prevState.text !== this.state.text) {
          this.handleCheck();
        }
      }
      
      onChange = e => {
        this.setState({
          text: e.target.value
        });
      };
      
      handleCheck = () => {
        // Clears running timer and starts a new one each time the user types
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.toggleCheck();
        }, 1000);
      }
      
      toggleCheck = () => {
        this.setState( prevState => ({ checked: !prevState.checked }));
      }
      
      render () {
        return (
          

    ) } } ReactDOM.render(, document.getElementById('root'));
    
    
    

提交回复
热议问题