0

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

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

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

4

2 回答 2

1

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

```

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

```

于 2017-01-30T22:23:42.433 回答
0

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

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} />
    }
}
于 2017-02-01T07:44:55.770 回答