在ReactJS功能组件中实现Lodash的反跳

问题描述

我正在尝试使用Lodash的debounce函数消除文本输入字段的变化。

import React from "react";
import debounce from 'lodash.debounce';

const Input = () => {

  const onChange = debounce((e) => {
    const { value } = e.target;
    console.log('debounced value',value)
  },1000)

  return (

    <input type="text" onChange={ onChange } />

  )
};

上面的代码引发以下错误

警告:出于性能原因,此综合事件被重用。如果看到此消息,说明您正在访问已发布/无效的综合事件的属性目标。设置为空。如果必须保留原始的合成事件,请使用event.persist()。

未捕获的TypeError:无法读取null的属性“值”

什么是正确的实现?

解决方法

何时使用参考文献有一些很好的参考案例:

  • 管理焦点,文本选择或媒体播放。
  • 触发命令性动画。
  • 与第三方DOM库集成。

避免将refs用于可以声明式完成的任何事情。

Refs and the DOM

您定义Input的方式,我假设它会在许多地方使用。所以,我会这样做:

import React from "react";
import debounce from 'lodash.debounce';

const Input = () => {

  // Debounced function
  // `printValue` only cares about last state of target.value
  const printValue = debounce(value => console.log(value),1000);

  // Event listener called on every change
  const onChange = ({ target }) => printValue(target.value);

  return <input type="text" onChange={ onChange } />;    

};
,

解决方法不是从事件中检索值,而是直接从带有引用的输入中检索值。

import React,{ useRef } from "react";
import debounce from 'lodash.debounce';

const Input = () => {

  const input = useRef( null )

  const onChange = debounce(() => {
    console.log('debounced value',input.current.value)
  },1000)

  return (

    <input ref={ input } type="text" onChange={ onChange } />

  )
};