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

cbd*_*per 2 javascript input reactjs react-hooks use-reducer

我的目标是使用 hook 实现 React 控制的输入useReducer

在减速器内部,我需要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>
  );
}
Run Code Online (Sandbox Code Playgroud)

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

这是错误:

警告:出于性能原因重用此合成事件。如果您看到此内容,则说明您正在访问target已发布/无效的合成事件的属性。这被设置为空。如果必须保留原始合成事件,请使用 event.persist()。请参阅react-event-pooling获取更多信息。

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

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

喜欢:

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

Den*_*ash 6

只需传递event.target.value即可,因为就像错误所述,合成事件不会持续存在。

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

编辑顽皮的风走了