Copy constructor(props){
...
this.handleClick = this.handleClick.bind(this)
this.handleClick = _.debounce(this.handleClick, debounceMillis)
}
render(){
<div onClick={this.handleClick}>
...
</div>
}
Copy import React, { Component } from 'react';
import debounce from 'lodash.debounce';
import PropTypes from 'prop-types';
class DebounceClick extends Component {
constructor(props) {
super(props);
const { children, debounceMillis, persist } = props;
const { onClick } = children.props;
const debounceHandle = debounce(onClick, debounceMillis);
if (persist) {
// in debounce source code, there is async code `setTimeout`
// so if we want to call e.persist(), we can only do here, or change debounce source code
this.handle = e => {
e.persist();
debounceHandle(e);
};
} else {
this.handle = debounceHandle;
}
}
noop() {}
render() {
const { children, active } = this.props;
return React.cloneElement(children, { onClick: active ? this.handle : this.noop });
}
}
DebounceClick.propTypes = {
debounceMillis: PropTypes.number,
persist: PropTypes.bool,
active: PropTypes.bool,
};
DebounceClick.defaultProps = {
debounceMillis: 500, // 500 is better, 200ms for most user, this will appear almost instantly
persist: false,
active: true, // false means not trigger onClick
};
export default DebounceClick;
Copy if (persist) {
// in debounce source code, there is async code `setTimeout`
// so if we want to call e.persist(), we can only do here, or change debounce source code
this.handle = e => {
e.persist();
debounceHandle(e);
};
} else {
this.handle = debounceHandle;
}
Copy <DebounceClick>
<div onClick={this.handleClick}>
...
</div>
</DebounceClick>