react组件封装input框的防抖处理

2023-11-11

防抖

防抖就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

项目中有些input框需要做防抖处理,防止每次输入都要发起请求或者做判断,也就是减少触发频率,以便提高性能或者说避免资源浪费

//防抖的方法
const debounceOther = (func, wait = 800) => {
  let timeout; // 定时器变量
  return function () {
    clearTimeout(timeout); // 每次触发时先清除上一次的定时器,然后重新计时
    timeout = setTimeout(() => {
      func(arguments);
    }, wait); // 指定 xx ms 后触发真正想进行的操作 handler
  };
};

在项目中经常会将许多方法或复用性较高的事件封装,然后在也页面引入

例:

防抖只需要看下面例子中getInputValue和inpurChange即可

这是基于antd封装的一个弹窗组件,在input框 需要判断输入后是否与原有值重复,不做防抖处理则输入一次判断一次 

这里是将有封装好的debounceOther函数的js文件直接引入到这个组件中使用了

import { debounceOther } from ".........";


class RelationModal extends Component {
  state = { visible: false, inputErr: '', inputValue: '' };
 
  getInputValue = debounceOther(() => {
    let { specSelect } = this.props;    //原有数据
    //是否存在相同的
    let index = specSelect.findIndex(item => item.group === this.state.inputValue);
    this.setState({
      inputErr: index === -1 ? "" : '节点名称不允许重复'
    })
  },500)

  //拿到inputValue input输入框有变化500毫秒后 调用防抖方法 
  inputChange = e => {
    this.setState({
      inputValue:e.target.value
    },()=>{
      this.getInputValue()
    }) 
  };

  handleOkCancel = (type) => {
    let { inputValue } = this.state;
    let { clickChange, modalType, specSelectList } = this.props;

    if (type === 'ok') {
      let arr = specSelectList.filter(item => item.checked === true);
      let nodeIndex = specSelect.findIndex((item) => item.group === inputValue);

      if (!inputValue) {
        message.warning('请输入节点名称!');
        return;
      } else if (!arr.length) {
        message.warning('请选择丰度数据!');
        return;
      } else if (nodeIndex !== -1) {
        message.warning("关联节点名称重复!");
        return;
      }
    }
    this.setState({
      inputErr: '',
      inputValue: ''
    });
    clickChange && clickChange(modalType, false, type, inputValue);
  };
  render() {
    let { inputValue, inputErr } = this.state;
    const {
      size,
      type,
      value,
      visible,
      toolName,
      modalType,
      labelName,
      defaulBool,
      inputStyle,
      specSelect,
      clickChange,
      toolNameStyle,
      labelNameStyle,
      specSelectList,
      tooltipStatus,
      inputAddonStyle,
      secondLabelName,
      secLabelNameStyle,
      ...other
    } = this.props;
    return (
      <Modal
        visible={visible}
        title="添加节点"
        cancelText="取消"
        okText="添加"
        className="netheat-modal-style"
        onOk={() => this.handleOkCancel('ok')}
        onCancel={() => this.handleOkCancel('cancel')}
      >
        <div
          style={{ display: "flex", alignItems: "center", ...inputAddonStyle }}
        >
          <span
            style={{
              color: "rgba(0, 0, 0, 0.6)",
              fontWeight: 500,
              ...labelNameStyle
            }}
          >
            {labelName}
          </span>
          <Input
            value={inputValue}
            onInput={this.getInputValue}
            onChange={this.inputChange} 
            style={{ width: 218, marginLeft: 10, ...inputStyle }}
            {...other}
          />
        </div>

        <div
          style={{ display: "flex", alignItems: "center", height: "12px", ...toolNameStyle }}
        >
          {inputErr}
          {/* {tooltipStatus ? ( */}
          {/* <span className="tool-name-style">{inputErr}</span> */}
          {/* ) : (
            ""
          )} */}
        </div>

        <div className="netheat-modal-spe-data-box">
          <div
            style={{
              color: "rgba(0, 0, 0, 0.6)",
              fontWeight: 500,
              ...secLabelNameStyle
            }}>

            {secondLabelName}
          </div>
          <div className="netheat-modal-spe-data">
            {
              (specSelectList || []).map((item, index) => (
                <li className="net-heatmap-modal" key={item.label}>
                  <Button size={size} onClick={() => clickChange && clickChange(index, item.checked, type)} className={`netheat-modal-spedata-node ${item.checked ? 'netheat-modal-spedata-node--active' : ''}`}>
                    {item.label}
                    <div className={`node-content-node-block ${item.checked ? '' : ' hide'}`}>
                      <div className="node-content-node-triangle"></div>
                      <div className="node-content-node-checked"></div>
                    </div>
                  </Button>
                </li>
              ))
            }
          </div>
        </div>
      </Modal>
    )
  }
}

效果如下:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

react组件封装input框的防抖处理 的相关文章

随机推荐