gpt4 book ai didi

javascript - 在 ReactJS 功能组件中实现 Lodash 的去抖动

转载 作者:行者123 更新时间:2023-12-02 02:40:45 24 4
gpt4 key购买 nike

我正在尝试使用 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 } />

)
};

上面的代码抛出以下错误:

Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().

Uncaught TypeError: Cannot read property 'value' of null

什么是正确的实现?

最佳答案

When to Use Refs There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Avoid using refs for anything that can be done declaratively.

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 } />;

};

关于javascript - 在 ReactJS 功能组件中实现 Lodash 的去抖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63665260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com