[英]React Component - debounce
尝试在具有随更改更新的输入字段的反应组件上创建延迟
这是我的 onChange 方法
handleOrderQtyKeyPress (e) {
var regex = /[^0-9]/
if (e.key.match(regex)) {
e.preventDefault();
}
if (this.state.orderQtyValue.toString().length == 3) {
e.preventDefault();
}
}
和react-bootstrap组件:
<FormControl
type='number'
min='0'
value={this.state.orderQtyValue}
onChange={this.handleOrderQtyChange}
onKeyPress={this.handleOrderQtyKeyPress}
style={styles.orderQtyValue}
/>
所以我尝试导入 lodash _.debounce 并在构造函数中应用
import debounce from 'lodash/debounce';
this.handleOrderQtyKeyPress = _.debounce(this.handleOrderQtyKeyPress.bind(this),1000);
我没有得到去抖。 我在这里想念什么?
我看到您使用了this
,因此我假设FormControl
位于有状态组件的渲染函数内。 在这种情况下,请确保您的绑定和去抖动发生在此有状态组件的constructor
中。
``
const Component extends React.Component {
constructor(props) {
super(props);
this.handleOrderQtyKeyPress = _.debounce(this.handleOrderQtyKeyPress.bind(this), 1000);
}
}
``
请阅读解释这是如何工作的评论
class Input extends Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
value: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
]),
}
state = {
value: '',
}
// When component receives updated `value` from outside, update internal `value` state.
componentWillReceiveProps(nextProps) {
this.setState({ value: nextProps.value });
}
// Store updated value localy.
onChange = (event) => {
this.setState({ value: event.target.value });
}
onBlur = (event) => {
// Trigger change to external env.
this.props.onChange(this.state.value);
// Also, don't forget to call `onBlur` if received from parent.
if (this.props.onBlur) {
this.props.onBlur(event);
}
}
render() {
return <input {...this.props} value={this.state.value} onChange={this.onChange} onBlur={this.onBlur} />
}
}
如果您想在 props 经常更改(而不是内部 state 更改)时轻松自动去抖动(或节流)组件,
我为此编写了一个小型包装器(缩小了1kb
),称为React-Bouncer :
import bouncer from '@yaireo/react-bouncer'
// uses 300ms `debounce` by default
const DebouncedYourComponent = bouncer(YourComponent)
当您对发送到组件的 props 的更新率没有太多控制,或者经常更新的根本原因未知时,这很有用。
(显然,首先要尝试对根本原因使用debounce
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.