如何使用 useReducer 实现反应控制输入?

How to implement a react controlled input using useReducer?

我的目标是使用 useReducer 挂钩实现 React 控制的输入。

在 reducer 内部,我需要 event.target.valueevent.target.selectionStart 来获取当前值和插入符号位置。所以我考虑过将 event 作为 payload 发送给 ON_CHANGE 操作。

这就是我正在尝试的:

https://codesandbox.io/s/optimistic-edison-xypvn

function reducer(state = "", action) {
  console.log("From reducer... action.type: " + action.type);
  switch (action.type) {
    case "ON_CHANGE": {
      const event = action.payload;
      const caretPosition = event.target.selectionStart;
      const newValue = event.target.value;
      console.log("From reducer... event.target.value: " + event.target.value);
      console.log(
        "From reducer... event.target.selectionStart: " + caretPosition
      );
      return newValue;
    }
    default: {
      return state;
    }
  }
}

export default function App() {
  console.log("Rendering App...");

  const [state, dispatch] = useReducer(reducer, "");

  return (
    <div className="App">
      <input
        value={state}
        onChange={event => dispatch({ type: "ON_CHANGE", payload: event })}
      />
    </div>
  );
}

它适用于输入的第一个字母,但在第二个字母时会中断。

这是错误:

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(). See react-event-pooling for more information.

我该怎么办?我需要在哪里调用event.persist()。我应该在 reducer 上执行此操作还是需要在 onChange() 处理程序内部将其作为参数发送之前执行此操作。

还是只发送这些属性而不是发送完整的 event 对象更好?

喜欢:

onChange={ event => 
  dispatch({ 
    type: "ON_CHANGE", 
    payload: {
      value: event.target.value,
      caretPosition: event.target.selectionStart
    }
  })
}

只需传递 event.target.value 即可,因为如错误所述,synthetic events 不会持续存在。

function reducer(state = "", action) {
  switch (action.type) {
    case "ON_CHANGE": {
      const newValue = action.payload;
      return newValue;
    }
    default: {
      return state;
    }
  }
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, "");

  return (
    <div className="App">
      <input
        value={state}
        onChange={event =>
          dispatch({ type: "ON_CHANGE", payload: event.target.value })
        }
      />
    </div>
  );
}