avoid constant re-render from “input” or “textarea” in react js

前端 未结 4 1454
面向向阳花
面向向阳花 2021-01-11 14:32

Currently in react js, when I want to bind a text area or an input with a \"state\", I will need to set the onChange method and setState() everytime user type in a single le

4条回答
  •  天涯浪人
    2021-01-11 15:05

    As @Chris stated, you should create another component to optimize the rerendering to only the specified component.

    However, there are usecases where you need to update the parent component or dispatch an action with the value entered in your input to one of your reducers.

    For example I created a SearchInput component which updates itself for every character entered in the input but only call the onChange function only if there are 3 characters at least.

    Note: The clearTimeout is useful in order to call the onChange function only when the user has stopped typing for at least 200ms.

    import React from 'react';
    
    class SearchInput extends React.Component {
      constructor(props) {
        super(props);
        this.tabTimeoutId = [];
        this.state = {
          value: this.props.value,
        };
    
        this.onChangeSearch = this.onChangeSearch.bind(this);
      }
    
      componentWillUpdate() {
        // If the timoutId exists, it means a timeout is being launch
        if (this.tabTimeoutId.length > 1) {
          clearTimeout(this.tabTimeoutId[this.tabTimeoutId.length - 2]);
        }
      }
    
      onChangeSearch(event) {
        const { value } = event.target;
    
        this.setState({
          value,
        });
    
        const timeoutId = setTimeout(() => {
          value.length >= this.props.minSearchLength ? this.props.onChange(value) : this.props.resetSearch();
          this.tabTimeoutId = [];
        }, this.props.searchDelay);
    
        this.tabTimeoutId.push(timeoutId);
      }
    
      render() {
        const {
          onChange,
          minSearchLength,
          searchDelay,
          ...otherProps,
        } = this.props;
    
        return  this.onChangeSearch(event)}
        />
      }
    }
    
    SearchInput.propTypes = {
      minSearchLength: React.PropTypes.number,
      searchDelay: React.PropTypes.number,
    };
    SearchInput.defaultProps = {
      minSearchLength: 3,
      searchDelay: 200,
    };
    
    export default SearchInput;
    

    Hope it helps.

提交回复
热议问题