如何消除受控输入的反跳? [英] How to debounce a controlled input?

查看:50
本文介绍了如何消除受控输入的反跳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正忙于应对输入和从lodash反弹.在大多数情况下,当我拥有表单时,我也有一个编辑选项,因此我需要一个受控组件来使用 value = {state ["targetValue"]} 填充输入,以便我可以填充和编辑字段.

I'm currently struggling with react inputs and debounce from lodash. Most of the time when I have a form I also have an edit option, so I need a controlled component to fill back the inputs using value={state["targetValue"]} so I can fill and edit the field.

但是,如果组件处于受控状态,则防抖动将不起作用.我在CodeSandbox上做了一个简单的示例: https://codesandbox.io/embed/icy-cloud-ydzj2?fontsize=14&hidenavigation=1&theme=dark

However, if the component is controlled debounce isn't working. I made a simple example on CodeSandbox: https://codesandbox.io/embed/icy-cloud-ydzj2?fontsize=14&hidenavigation=1&theme=dark

代码:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { debounce } from "lodash";

import "./styles.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      title: "",
      editMode: false
    };
    this.debouncedEvent = React.createRef();
  }

  debounceEvent(_fn, timer = 500, options = null) {
    this.debouncedEvent.current = debounce(_fn, timer, options);
    return e => {
      e.persist();
      return this.debouncedEvent.current(e);
    };
  }

  componentWillUnmount() {
    this.debouncedEvent.current.cancel();
  }

  onChangeValue = event => {
    const { name, value } = event.target;

    this.setState(() => {
      return { [name]: value };
    });
  };

  onRequestEdit = () => {
    this.setState({ name: "Abla blabla bla", editMode: true });
  };

  onCancelEdit = () => {
    if (this.state.editMode) this.setState({ name: "", editMode: false });
  };

  onSubmit = event => {
    event.preventDefault();
    console.log("Submiting", this.state.name);
  };

  render() {
    const { name, editMode } = this.state;
    const isSubmitOrEditLabel = editMode ? `Edit` : "Submit";
    console.log("rendering", name);
    return (
      <div className="App">
        <h1> How to debounce controlled input ?</h1>
        <button type="button" onClick={this.onRequestEdit}>
          Fill with dummy data
        </button>
        <button type="button" onClick={this.onCancelEdit}>
          Cancel Edit Mode
        </button>
        <div style={{ marginTop: "25px" }}>
          <label>
            Controlled / Can be used for editing but not with debounce
          </label>
          <form onSubmit={this.onSubmit}>
            <input
              required
              type="text"
              name="name"
              value={name}
              placeholder="type something"
              // onChange={this.onChangeValue}
              onChange={this.debounceEvent(this.onChangeValue)}
            />
            <button type="submit">{isSubmitOrEditLabel}</button>
          </form>
        </div>
        <div style={{ marginTop: "25px" }}>
          <label> Uncontrolled / Can't be used for editing </label>
          <form onSubmit={this.onSubmit}>
            <input
              required
              type="text"
              name="name"
              placeholder="type something"
              onChange={this.debounceEvent(this.onChangeValue)}
            />
            <button type="submit">{isSubmitOrEditLabel}</button>
          </form>
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

推荐答案

所以...显然,没有解决方案.输入从状态中获取值.防抖动会阻止状态触发.

So... Apparently, there's no solution. the input takes the value from the state. While debounce prevents the state to trigger.

我使用ReactDOM进行了变通.

I made a workaround using ReactDOM.

import ReactDOM from "react-dom";

export const setFormDefaultValue = (obj, ref) => {
  if (ref && !ref.current) return;

  if (!obj || !obj instanceof Object) return;

  const _this = [
    ...ReactDOM.findDOMNode(ref.current).getElementsByClassName("form-control")
  ];

  if (_this.length > 0) {
    _this.forEach(el => {
      if (el.name in obj) el.value = obj[el.name];
      else console.error(`Object value for ${el.name} is missing...`);
    });
  }
};

然后使用:

this.refForm = React.createRef();
setFormDefaultValue(this.state, refForm)

这样,我可以使用状态默认值填写表单,然后继续使用去抖动功能.

This way I can fill my form with the state default value and continue using debounce.

这篇关于如何消除受控输入的反跳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆