React-Semantic UI 调度事件不工作

React-Semantic UI dispatch event not working

我正在创建一个具有反应语义的文本输入 UI,它会在单击按钮时放置文本。一切正常,只是此操作不会触发 onchange 事件,因此不会更新状态。

这是我将文本附加到输入的函数

const putTextAtCursor = (text, inputID) => {
  let inputElement = document.getElementById(inputID);
  console.log({ inputElement, inputID });
  let cursorPosition = 0;
  if (document.selection) {
    inputElement.focus();
    let selectionRange = document.selection.createRange();
    selectionRange.moveStart("character", -inputElement.value.length);
    cursorPosition = selectionRange.text.length;
  } else if (
    inputElement.selectionStart ||
    inputElement.selectionStart == "0"
  ) {
    cursorPosition = inputElement.selectionStart;
  }
  let origValue = inputElement.value;
  let newValue =
    origValue.substr(0, cursorPosition) +
    text +
    origValue.substr(cursorPosition);

  inputElement.value = newValue;
  let start = inputElement.selectionStart;
  inputElement.selectionStart = inputElement.selectionEnd = start + text.length;
  let event = new UIEvent("change");
  inputElement.dispatchEvent(event);
  inputElement.focus();
};

dispatchEvent 似乎没有被解雇。完整演示是 here

如何解决?

您应该使用此代码:

let input = inputElement;
let lastValue = input.value;
input.value = newValue;
let event = new Event('input', { bubbles: true });
let tracker = input._valueTracker;
if (tracker) {
    tracker.setValue(lastValue);
}
input.dispatchEvent(event);

改为:

  inputElement.value = newValue;
  let start = inputElement.selectionStart;
  inputElement.selectionStart = inputElement.selectionEnd = start + text.length;
  let event = new UIEvent("change");
  console.log(inputElement.onchange, "io");
  inputElement.dispatchEvent(event);

这是因为 React 的版本。了解这个情况的一切都在这个post:https://github.com/facebook/react/issues/11488