簡體   English   中英

React 組件 - 去抖動

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM