【问题标题】:React Component - debounceReact 组件 - 去抖动
【发布时间】:2017-06-16 04:48:28
【问题描述】:

尝试在具有随更改更新的输入字段的反应组件上创建延迟

这是我的 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);

我没有得到去抖动。我在这里想念什么?

【问题讨论】:

  • 你想达到什么目的?你为什么要对更改事件进行去抖动?
  • 去抖以防止每次在输入字段中输入数字时触发 onChange。

标签: javascript reactjs ecmascript-6 react-bootstrap debounce


【解决方案1】:

我看到你使用this,所以我假设FormControl 在你的有状态组件的渲染函数中。在这种情况下,请确保您的绑定和去抖动发生在此有状态组件的 constructor 中。

```

const Component extends React.Component {
   constructor(props) {
     super(props);
     this.handleOrderQtyKeyPress = _.debounce(this.handleOrderQtyKeyPress.bind(this), 1000);
   }
}

```

【讨论】:

    【解决方案2】:

    请阅读解释其工作原理的评论

    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} />
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 2017-05-03
      • 2020-04-28
      • 2021-06-30
      • 2016-07-17
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多