Perform debounce in React.js

前端 未结 30 1561
礼貌的吻别
礼貌的吻别 2020-11-22 04:11

How do you perform debounce in React.js?

I want to debounce the handleOnChange.

I tried with debounce(this.handleOnChange, 200) but it doesn\'t

30条回答
  •  无人及你
    2020-11-22 04:41

    After struggling with the text inputs for a while and not finding a perfect solution on my own, I found this on npm: react-debounce-input.

    Here is a simple example:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import {DebounceInput} from 'react-debounce-input';
    
    class App extends React.Component {
    state = {
        value: ''
    };
    
    render() {
        return (
        
    this.setState({value: event.target.value})} />

    Value: {this.state.value}

    ); } } const appRoot = document.createElement('div'); document.body.appendChild(appRoot); ReactDOM.render(, appRoot);

    The DebounceInput component accepts all of the props you can assign to a normal input element. Try it out on codepen

    I hope it helps someone else too and saves them some time.

提交回复
热议问题